PHP programming language provides arrays in order to store multiple items in a single variable. Arrays are very useful which makes the storage, management, and manipulation of series of data easy. The PHP provides associative arrays which is a type of array. Associative arrays are used to store items as values and keys.
The associative arrays can be used for different purposes like list, vector, distionary, collection, stack, queue etc. This makes the associative arrays very popular and useful.
Create Associative Array
An associative array can be created in different ways. The first way to create an associative array is by providing the array items in a single statement. This single statement can be a single line or multiple lines. In the following example, we will create an associative array with person names and their ages.
$age = array("ismail"=>37 , "ahmet"=>8 , "elif"=>12);
Alternatively, an associative array can be created by adding the items one by one in multiple statements. In this case, there is no need to use the array statement.
$age["ismail"]=37;
$age["ahmet"]=8;
$age["elif"]=12;
Create Mixed Type Associative Array
Another powerful feature of the associative array is the items can be of different types. The key or items can be an integer, string, etc. for every different item. This type of associative arrays called a mixed type associative array. This can be very useful to store different objects in a single array.
$person= array("name"=>"ismail","age"=>37);
Add Item To Associative Array
New items can be easily added to the associative arrays. Just provide the item key and the value which is set. In the following example, the new item with the key “country” and value “Turkey” added to the associative array named $person.
$person= array("name"=>"ismail","age"=>37);
$person["country"]="Turkey";
Use Associative Array Items
The associative array items can be retrived and used easily by using the keys. In order to get an item value just provide the key. The retuned value can be assigned into a variable or used directly.
$person= array("name"=>"ismail","age"=>37);
$name = $person["name"];
echo $person["name"];
Loop Associative Array
The storage of multiple items in a single variable makes arrays very useful. These items can be looped using different loop mechanisms. The loop makes to iterate on every item of the associative array.
$age = array("ismail"=>37 , "ahmet"=>8 , "elif"=>12);
foreach($age as $name => $value){
echo $name." age is ".$value;
}