What is an Array?
All related values that are stored inside a variable is called an array.
Types of Array in PHP
- Indexed Array
- Associative array
Index Array:
Example for indexed array
1 |
$char = array('Kritika Shrivastava', 'Devesh Srivastava', 'Monica Singh'); |
To print indexed array
We can not use echo or print to print an array. We use a function <span class=”keyword”>print_r</span> to print an array
Example
1 2 |
$char = array('Kritika Shrivastava', 'Devesh Srivastava', 'Monica Singh'); print_r($char); |
Output :
1 |
Array ( [0] => Kritika Shrivastava [1] => Devesh Srivastava [2] => Monica Singh ) |
Here each array element has a number starting from zero. This number is known as an array index. The array keyword is a traditional way to create an array in PHP. But from PHP 5.4 you can use a shorthand to create an array. A new way of creating an array from PHP 5.4
Adding values to array operator.
1 2 3 4 |
$char = ['Kritika Shrivastava', 'Devesh Srivastava', 'Monica Singh']; $char[] = 'Shruti Shrivastava'; $char[] = 'Dan'; print_r($char); |
When we run this PHP will automatically assign next available number to the elements of array added.
>>To display the second element of an array we will write
1 |
echo $char[1]; |
Associative Array:
In index array, we have a numeric index but in an associative array instead of numeric index, each array element is identified by a string. Associative array stores a set of key-value pair. Let’s look at the example
1 2 3 4 5 6 |
$desc = [ 'name' => 'Kritika', 'age'=> '27', 'Gender' => 'Female', ]; echo $desc['name']; |
Note: Associative array works exactly the same as an indexed array. There is a major difference between an associative array and indexed array is you can not put an associative array inside double quotes.If you try doing that:
Example
1 2 3 4 5 6 7 |
$desc = [ 'name' => 'Kritika', 'age'=> '27', 'Gender' => 'Female', ]; echo "The name is $desc['name']"; |
When you run this you will get a fatal error. To get rid of this enclose associative array inside curly braces.
1 2 3 4 5 6 |
$desc = [ 'name' => 'Kritika', 'age'=> '27', 'Gender' => 'Female', ]; echo "The name is {$desc['name']}"; |
Now this code works fine