PHP Associative Arrays



PHP Associative Arrays :

  1. In the numeric array we used to have numeric index for an array. In the associative array we can have named index instead of numeric index.
  2. Associative Arrays is more above name(key) and value pair.

Example #1 : Associative Array Using Array function

Suppose we need to store the age of the employees then instead of using index we can use name of the employee as index.

<html>
<body>
<?php
$ages = array( 
    "Arun" => 2000, 
    "Atul" => 1000, 
    "Anis" => 5000
);
echo "Age of Arun : ". $ages['Arun'] . "<br />";
echo "Age of Atul : ". $ages['Atul'] . "<br />";
echo "Age of Anis : ". $ages['Anis'] . "<br />";
?>
</body>
</html>

Output :

Age of Arun : 2000
Age of Atul : 1000
Age of Anis : 5000

Example #2 : Associative Array direct initialization

Now here is another alternate method to initialize array.

<html>
<body>
<?php
$ages['Arun'] =  2000; 
$ages['Atul'] =  1000; 
$ages['Anis'] =  5000;
echo "Age of Arun : ". $ages['Arun'] . "<br />";
echo "Age of Atul : ". $ages['Atul'] . "<br />";
echo "Age of Anis : ". $ages['Anis'] . "<br />";
?>
</body>
</html>

Output :

Age of Arun : 2000
Age of Atul : 1000
Age of Anis : 5000