PHP Associative Array

PHP allows you to associate name/label with each array elements using => symbol. It is also called key-value pair array.

Creating PHP Associative Array

 array() function is used to create associative array.

There are two ways to create an associative array as shown below.

$age = array("John"=>"35", "Ben"=>"37", "Neil"=>"43");


$age['John'] = "35";
$age['Ben'] = "37";
$age['Neil'] = "43";

Associative arrays are used to store key value pairs. 

Accessing the PHP Associative Array elements

$age = array("John"=>"35", "Ben"=>"37", "Neil"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";

Traversing PHP Associative Array

We can traverse associative arrays using foreach loop.


/* Creating an associative array */
$age = array("Anil"=>25, "Jay"=>29,
				"Neil"=>36, "Smith"=>33,
/* Looping through an array using foreach */
echo "Looping using foreach: <br>";
foreach ($age as $person => $age_num){
	echo $person." is ".$age_num." years old.<br>";

Traversing PHP Associative Array Example – Output