3/31/15

PHP Associative Array


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 can not follow any types of order.

There are two ways to create an associative array

Eg i
 
   <?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.
OR
 
   <?php
  $Personage['Ravi']=30;
  $Personage['Vishu']=21;
  $Personage['Harmeet']=43;    
  echo "Harmeet is ".$Personage["Ravi"]."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

Eg ii
   <?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.
Eg iii (Using foreach display index of state and value the of state)
   <?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

0 comments:

Post a Comment

FIND US ON FACEBOOK

FIND US ON Twitter