Associative Array
PHP allows you to associate name/label with each array of elements in PHP using => symbol. In such a way, you can easily remember the element because each element is represented by label than an incremented number.

Definition :
There is two Method to define an associative array:
First Method :
$ages=array("Kapil"=>"25","Lakhan"=>"36","Sonia"=>"18");
Second Method :
$ages["Kapil"]="25";
$ages["Lakhan"]="36";
$ages["Sonia"]="18";
Example
File Name :first_associativearray.php
<?php
$ages=array("Kapil"=>"25","Lakhan"=>"36","Sonia"=>"18");
echo "Kapil Age: ".$ages["Kapil"]."<br/>";
echo "Lakhan Age: ".$ages["Lakhan"]."<br/>";
echo "Sonia Age: ".$ages["Sonia"]."<br/>";
?>
Output:
Kapil Age: 25
Lakhan Age: 36
Sonia Age: 18
File Name: second_associativearray.php
<?php
$ages["Kapil"]="25";
$ages["Lakhan"]="36";
$ages["Sonia"]="18";
echo "Kapil Age: ".$ages["Kapil"]."<br/>";
echo "Lakhan Age: ".$ages["Lakhan"]."<br/>";
echo "Sonia Age: ".$ages["Sonia"]."<br/>";
?>
Output:
Kapil Age: 25
Lakhan Age: 36
Sonia Age: 18
Traversing PHP Associative Array / Using Loops with Associative Arrays
- With the help of PHP for each loop, we can easily traverse the elements of PHP associative array.
- Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. We can use the foreach loop or the list() and each() constructs.
- The foreach loop has a slightly different structure when using associative arrays. We can use it exactly as we did in the previous example, or we can incorporate the keys as well:
<?php
$ages=array("Kapil"=>"25","Lakhan"=>"36","Sonia"=>"18");
foreach($ages as $key => $ag) {
echo "Key: ".$key." Value: ".$ag."<br/>";
}
?>
Output:
Key: Kapil Age: 25
Key: Lakhan Age: 36
Key: Sonia Age: 18
