PHP - Associative Arrays
In PHP, associative array is used to store data in key-value pairs. It is used to hold multiple key-value pairs in a single variable.
Create an Associative Array
An associative array can be created using array() keyword. It can be initialized at the time of creation by specifying key-value pairs within the array() keyword and separated by comma (,) or it can be initialized later by specifying value using key.
Alternatively, [] can also be used instead of array().
Syntax
//Creating an empty associative array $MyArray = array(); $MyArray = []; //Creating an associative array with initialization $MyArray = array(key1=>value1, key2=>value2, ...); $MyArray = [key1=>value1, key2=>value2, ...]; //initialization after creation of array $MyArray[key] = value;
Access element of an associative array
An element of an associative array can be accessed with it's key. The example below illustrates the way of accessing data in an associative array.
<?php //creating an array with 3 elements $MyArray = array(101=>"Red", 102=>"Blue", 103=>"Green"); //adding 4th and 5th elements $MyArray[104] = "Black"; $MyArray[105] = "White"; echo "101 => ".$MyArray[101]."\n"; echo "102 => ".$MyArray[102]."\n"; echo "103 => ".$MyArray[103]."\n"; echo "104 => ".$MyArray[104]."\n"; echo "105 => ".$MyArray[105]."\n"; ?>
The output of the above code will be:
101 => Red 102 => Blue 103 => Green 104 => Black 105 => White
Modify the value of a key
The value of any key of an associative array can be changed using its key and assigning a new value.
<?php $MyArray = array(101=>"Red", 102=>"Blue", 103=>"Green"); //changing the value of a key $MyArray[101] = "Yellow"; //displaying the array print_r($MyArray); ?>
The output of the above code will be:
Array ( [101] => Yellow [102] => Blue [103] => Green )
Loop over an Associative Array
By using foreach loop, each elements of an associative array can be accessed. Consider the example below:
<?php $MyArray = array(); $MyArray[101] = "Red"; $MyArray[102] = "Blue"; $MyArray[103] = "Green"; echo "MyArray contains: \n"; foreach($MyArray as $x => $x_value) echo "Key=". $x ." Value=". $x_value."\n"; ?>
The output of the above code will be:
MyArray contains: Key=101 Value=Red Key=102 Value=Blue Key=103 Value=Green
Accessing an array inside double quotes
A value from the associative array can be accessed inside double quotes by enclosing it between curly braces. See the example below:
<?php $arr = array('name' => 'John', 'age' => 25); //using array elements inside double quotes echo "{$arr['name']} is {$arr['age']} years old."; ?>
The output of the above code will be:
John is 25 years old.
Complete PHP Array Reference
For a complete reference of all PHP Array functions, see the complete PHP Arrays Reference.