In terms of functionality, associative arrays are fairly similar to numeric arrays, however, they differ in terms of the index. The index of an associative array will be a string, allowing you to create a strong link between key and value.
PHP Associative Array Definition
There are two ways of defining PHP associative array:
1.
$age=array("John"=>"55","Bean"=>"22","Henry"=>"41");
<h2> Example of Associative Array</h2> <?php $age=array("John"=>"55","Bean"=>"22","Henry"=>"41"); echo "John age is: ".$age["John"]."<br/>"; echo "Bean age is: ".$age["Bean"]."<br/>"; echo "Henry age is: ".$age["Henry"]."<br/>"; ?>
2.
$age["John"]="55";
$age["Bean"]="22";
$age["Henry"]="41";
<h2> Example of Associative Array</h2> <?php $age["John"]="55"; $age["Bean"]="22"; $age["Henry"]="41"; echo "John age is: ".$age["John"]."<br/>"; echo "Bean age is: ".$age["Bean"]."<br/>"; echo "Henry age is: ".$age["Henry"]."<br/>"; ?>
Note: When printing, don’t put the associative array inside a double quote; otherwise, it won’t return anything.
Traversing PHP Associative Array
In PHP array can be traversed easily by using foreach loop. Let’s look at a simple example of traversing the entire PHP array.
<h2> Traversing Associative Array</h2> <?php $age=array("John"=>"55","Bean"=>"22","Henry"=>"41"); foreach($age as $k => $v) { echo "Key: ".$k." Value: ".$v."<br/>"; } ?>