How To Create Associative Arrays In PHP

How To Create Associative Arrays In PHP

·

1 min read

In this tutorial, we will be learning about associative arrays.

What Are Associative Arrays?

Associative arrays are arrays with named keys; instead of the default numbers, we give each key a string value.

How To Create An Associative Array? There are three ways you can create an associative array. Example

<?php
$a = array("a"=>"a", "b"=>"b", "c"=>"c");
$b = ["c"=>"c", "a"=>"a", "t"=>"t"];
$c["b"] = "b";
$c["a"] = "a";
$c["r"] = "r";
?>

In the above example, arrays $a, $b and $c were all created with different legitimate syntax.

Looping Through Associative Arrays

As you know, one benefit of arrays is that we can loop through their values. One way we can loop through an associative array without worrying about the key of their keys is by using the for-each loops as seen below. Example

<?php
$a = ["q"=>"b", "w"=>"a", "e"=>"t"];
foreach($a as $a)
{
echo $a;
echo "<br>";
}
?>

Result

1.png In the above example, we do not need to care what the keys of $a are equal to; the for-each loop will work equally successfully.