PHP Associative Array

Associative Array performs same function as that of Indexed Array but unlike Indexed Array which uses Numeric Index, Associative Array uses a String Index for referring to an element of array. In PHP, if you want to create an associative array, you are required to use the => operator.

Associative Array can be specified in following two different ways

  • With the use of array() construct
  • With the use of array operator[]

Associative Array Using Array() Construct

Syntax

$arrayName=array(key1 => value1,key2=> value2,....);

Associative Array Using Array() Example

<?php 
$myInfo = array("Name"=> "Jimi","Class"=> "Seventh", "Age" => 11);
echo "My Name is:".$myInfo["Name"]."and my age is:".myInfo["Age"];
?> 

This will produce following result

My Name is:Jimi and my age is:11

Associative Array Using Array operator[]

Syntax

$arrayName=array();
$arrayName[key1]=value1;
$arrayName[key2]=value2;
.....

Associative Array Using Array operator[] Example

<?php 
$myInfo=array();
$myInfo["Name"]="Jimi";
$myInfo["Class"]="Seventh";
$myInfo["Age"]=11;
echo "My Name is:".$myInfo["Name"]."and my class is:".myInfo["Class"];
?> 

This will produce following result:

My Name is:Jimi and my class is:Seventh

Count Number of Elements in an Associative Array

In PHP Associative Array, array count can be done using count() function.

Count Number of Elements in an Associative Array Example

<?php 
$myInfo = array("Name"=> "Jimi","Class"=> "Seventh", "Age" => 11);
echo count($myInfo);
?> 

This will produce following result

3

Display elements in an Associative Array using Foreach

In PHP Associative Array, array elements can be display using Foreach.

Associative Array using Foreach Example

<?php 
$myInfo = array("Name"=> "Jimi","Class"=> "Seventh", "Age" => 11);
foreach($myInfo $key=>$value){
echo $key."is".$value;
echo "</br>";
?> 

This will produce following result

Name is Jimi
Class is seventh
Age is 11