PHP (Core & Framework)

How to use Associative Arrays in PHP

associative array php

Associative arrays are used to store key value pairs. For example, to store the age of different members of a family in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective member’s names as the keys in our associative array, and the value would be their respective age.

There are two ways to create an associative array:

Example:
$age = array(“Anil”=>”45”, “Suita”=>”39”, “Ravina”=>”23”);

or 

$age[‘Anil’] = “45”;
$age[‘Suita’] = “39”;
$age[‘Ravina’] = “23”;
/* Accessing the Associative arrays’s elements directly */
echo “Anil is “ . $age[‘Anil’] . ” years old.”;

Loop Through an Associative Array

To print all the values of an associative array, you can use a foreach loop, like this:
<?php
$age = array(“Anil”=>”45”, “Suita”=>”39”, “Ravina”=>”23”);

foreach($age as $x => $x_value) {
    echo “Key=” . $x . “, Value=” . $x_value;
    echo “<br>”;
}
?>

Comment here

74 + = 77