PHP Associative Arrays

Definition : Associative arrays are arrays that hold keys and values pairs. Here we can assign our own keys to array
elements. Here user has freedom to assigned with user defined key of string type.

There are two methods (ways) of creating Associative Arrays

First Method :

<?php
/* 
    1st - direct array initialization
*/
$rank = array("Java"=>1, "C"=>2, "Python"=>3,"C++"=>4,"C#"=>5);

?>

Second Method :

<?php
/* 
    2nd - distributed array initialization
*/
$marks["maths"] = 90;
$marks["physics"] = 80;
$marks["computer"] = 85;

?>

Accessing Associative array :

<?php
/* 
    Accessing array
*/
echo "Accessing the 2nd array...";
echo $marks["maths"], "<br>";
echo $marks["physics"], "<br>";
echo $marks["computer"], "<br>";

echo "Accessing the 1st array...";
echo $rank["Java"], "<br>";
echo $rank["C"], "<br>";
echo $rank["Python"], "<br>";

?>

Traversing PHP Associative Array :

Traversing of an array denote iterate it from first element to the last element of the array.
To traverse an associative array we use for loop or foreach loop.

Using for loop :

<?php

$rank = array("Java"=>1, "C"=>2, "Python"=>3,"C++"=>4,"C#"=>5);

// find size of the array
$size = count($rank);

// getting the array of keys/index strings
$keys = array_keys($rank);

// using the for loop
for($i = 0; $i < $size; $i++)
{
    echo "Rank of " .$keys[$i]." is  ". $rank[$keys[$i]]."  <br>";
}

?>

Using the foreach loop :

<?php

$rank = array("Java"=>1, "C"=>2, "Python"=>3,"C++"=>4,"C#"=>5);

// using the foreach loop
foreach($rank as $key => $value)
{
    echo "Rank of ".$key ." is ". $value ." <br>";
}

?>

Advantages of Associative Array :

  1. We can set index value as string format that is more meaningful like $marks[“maths”] = 90;
  2. User can set index value as per his/her convenience that is also useful for other developer.
  3. It is very easy to remember index data.
Share This!

Leave a Reply

Your email address will not be published.