PHP Associative Array

Associative arrays are very similar to numeric arrays in terms of functionality but they are different in terms of their index. In associative array, to access the array values, the user defined keys are used instead of index numbers. Associative array will have their index as string so that user can establish a strong association between key and values. For example :
 $array_name = array(key1 => value1, key2 => value2, key2 => value3, ...., keyN => valueN);
Example :
<?php
  
  $age = array("John"=> 25, "Sam" => 23, "Marry" => 30, "Luci" => 29);

  echo "John's Age : " . $age['John'] . "<br/>";
  echo "Sam's Age : " . $age['Sam'] . "<br/>";
  echo "Marry's Age : " . $age['Marry'] . "<br/>";
  echo "Luci's Age : " . $age['Luci'] . "<br/><br/>";


  $salary["John"] = 20000;
  $salary["Sam"] = 18000;
  $salary["Marry"] = 40000;
  $salary["Luci"] = 36000;
  
  echo "John's salary : " . $salary['John'] . "<br/>";
  echo "Sam's salary : " . $salary['Sam'] . "<br/>";
  echo "Marry's salary : " . $salary['Marry'] . "<br/>";
  echo "Luci's salary : " . $salary['Luci'] . "<br/><br/>";

?>
Output :

John's Age : 25
Sam's Age : 23
Marry's Age : 30
Luci's Age : 29

John's salary : 20000
Sam's salary : 18000
Marry's salary : 40000
Luci's salary : 36000

The count() function :

The count() function is used to return the length or the number of elements of an array. for example :
<?php

  $age = array("John"=> 25, "Sam" => 23, "Marry" => 30, "Luci" => 29);
  echo count($age);

?>
Output :

4

Loop Through the Associative Array :

By using the foreach loop we can get all the values of an associative array. For example :
<?php
  $age = array("John"=> 25, "Sam" => 23, "Marry" => 30, "Luci" => 29);

  foreach($age as $x_key => $x_value) {
    echo "Key = " . $x_key . ", Value = " . $x_value . "<br/>";
  }
?>
Output :

Key = John, Value = 25
Key = Sam, Value = 23
Key = Marry, Value = 30
Key = Luci, Value = 29


Next Topic :