Home >>Advance PHP Tutorial >PHP Associative Array

PHP Associative Array

Associative array PHP

In associative array index( key ) can initialized according to Your own requirement.

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

In this association use ( => ) sign to define index and values.

Associative arrays does not follow any types of order.

There are two ways to create an associative array

First Way to define associative Array

 <?php
	 
$Personage=array("Ravi"=>"30","Vishu"=>"21","Harmeet"=>"43");
	
 echo "Ravi is ".$Personage["Ravi"]."Years old"; 
 
?>
Output Ravi is 30 Years old

In the above example This is first way to create associative array. We create an array and store in( $Personage). here the key(index) is user defined, numerical key is not always best way to do it. Inside echo statement ($Personage["Ravi"]) is used to fetch the age of ravi. In this program "Ravi" is act as index/key of an array.

Another Way to define associative Array

 <?php
	
$Personage['Ravi']=30;
	
$Personage['Vishu']=21;
	
$Personage['Harmeet']=43;	 		
	
echo "Harmeet is ".$Personage["Harmeet"]."Years old"; 
 
?>

Output Harmeet is 43 Years old

This is the second way to create an associative array. Value assign to an array each Line. This method is long So we use Previous method.


Loop Through an Associative Array

To loop through and print all the values of an associative array, you must use a foreach loop

<?php

$state=array("Dl"=>"Delhi","Hr"=>"Haryana","Pn"=>"Punjab","Br"=>"Bihar");	
     
 foreach($state as $val)

       {

	echo $val." ";

       }
		
?>

Output Delhi Haryana Punjab Bihar

In the above example foreach loop is used to loop through arrays Defined an associative Array variable ($state) states are defined inside the array. Foreach loop is used. the value of the current array element is assigned to $val . Print the value of elements of array.

Using foreach display index(key) value of $state array

<?php
 
$state=array("Dl"=>"Delhi","Hr"=>"Haryana","Pn"=>"Punjab","Br"=>"Bihar");	
     
foreach($state as $key=>$val)

{

echo $key."---".$val."<br/>";

}
		
?>

Output Dl --- Delhi Hr --- Haryana Pn --- Punjab Br --- Bihar

No Sidebar ads