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
Syntax
$arrayName=array(key1 => value1,key2=> value2,....);
<?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
Syntax
$arrayName=array(); $arrayName[key1]=value1; $arrayName[key2]=value2; .....
<?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
In PHP Associative Array, array count can be done using count() function.
<?php $myInfo = array("Name"=> "Jimi","Class"=> "Seventh", "Age" => 11); echo count($myInfo); ?>
This will produce following result
3
In PHP Associative Array, array elements can be display using Foreach.
<?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