Associative Array in PHP

PHP associative array is that array whose index is represented by string. It stores items in association with key values. The structure of an associative array is given below…

$a = array(‘id’=>1,’name’=>”Sayeed”,’age’=>24);

Here, the array index is represented by string. So, the variable $a is a PHP associative array variable.

Associative array in PHP

Associative array in PHP

How to print the elements of an associative array

PHP associative array elements can be printed in two ways. These are…

  1. Using index value directly.
  2. Using foreach loop statement.

Print associative array elements using index directly

An associative array elements can be printed using its index value directly. See below example…


<?php 

$a = array('id'=>1,'name'=>"Sayeed",'age'=>24);

echo "ID = ".$a['id'];

echo "<br>Name = ".$a['name'];

echo "<br>Age = ".$a['age'];

?>

Output

ID = 1
Name = Sayeed
Age = 24

Here, the elements of array variable $a are being printed using index value directly. See carefully, the index value has been kept into inverted comma but it is not mandatory if the index value is a single word. But if the index value contains multiple words, the inverted comma must be used otherwise PHP will show an error message.

Print associative array elements using foreach loop statement

Associative array elements can be printed using PHP foreach loop statement so easily. See below example where foreach loop statement is being used to print PHP associative array element.


<?php 

$a = array('id'=>1,'name'=>"Sayeed",'age'=>24);

foreach($a as $value){
  echo $value."<br>";

}

?>

Output

1
Sayeed
24

PHP foreach loop statement can also be used to print the key and the value of an associative array at the same time. The above example can be written as below to print key and value of an associative array.


<?php 

$a = array('id'=>1,'name'=>"Sayeed",'age'=>24);

foreach($a as $key => $value){
  echo $key." = ".$value."<br>";
}

?>

Output  

id = 1
name = Sayeed
age = 24

PHP associative array has been explained in this article from very beginning. If you feel any problem to understand PHP associative array, feel free to contact with me from Contact us page. I’ll try my best to stay with you. PHP multidimensional array, another important array in PHP programming, will be explained in next tutorial. Spend some time to study that article and improve your idea about PHP multidimensional array.

No Responses

Leave a Comment

Your email address will not be published. Required fields are marked *