Facebook Page Twitter Page LinkedIn Page
× PHP Tutorial PHP Advanced PHP Resources


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 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.

Syntax

//Creating an empty associative array.
$MyArray = array();  

//Creating an associative array with initialization.
$MyArray = array(key1=>value1, key2=>value2, ...); 

//initialization after creation of array
$MyArray[key] = value;

Access element of an associative array

An element of an Array can be accessed with it's key. Below mentioned example 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");

//Add 4th and 5th elements
$MyArray[104] = "Black";
$MyArray[105] = "White";

echo "101:" . $MyArray[101]."\n";
echo "103:" . $MyArray[103]."\n";
echo "105:" . $MyArray[105]."\n";
?>

The output of the above code will be:

101:Red
103:Green
105:White

Change 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";

echo "101:" . $MyArray[101]."\n";
echo "102:" . $MyArray[102]."\n";
echo "103:" . $MyArray[103]."\n";
?>

The output of the above code will be:

101:Yellow
102:Blue
103:Green

Loop over an Associative Array

By using foreach loop, each elements of an associative array can be accessed.

Foreach Loop over an Array

In the below example, foreach loop is used to access all elements of an associative array.

<?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