The element of an Array in PHP by default are accessed by the index number i.e. the position in which the element or value is stored in the array.
For example :
<?php
$temperature = array(10, 20, 30, 25);
echo "Delhi temperature : ".$temperature[0];
echo "<br>Mumbai temperature : ".$temperature[1];
echo "<br>Chennai temperature : ".$temperature[2];
echo "<br>Kolkatta temperature : ".$temperature[3];
?>
The output will be:
Delhi temperature : 10
Mumbai temperature : 20
Chennai temperature : 30
Kolkatta temperature : 25
Now if we want to know the temperature of the particular city it will be very hard to remember the index of the city.
Now instead of using the index to get the value of array we will assign a "key" to the "value" of an array before saving the array, and will use this key to get the particular value.
For example:
<?php
$temperature = array('Delhi'=>10,'Mumbai'=>20,'Chennai'=>30,'Kolkatta'=>25);
foreach($temperature as &key=>$value)
echo &key."temperature : ".$value."<br>";
?>
The output will be:
Delhi temperature : 10
Mumbai temperature : 20
Chennai temperature : 30
Kolkatta temperature : 25
This is called "associative array".
0 Comment(s)