Iterate over an associative array in PHP
This post will discuss how to iterate over an associative array in PHP.
1. Using foreach
construct
A simple solution to looping through an associative array is using the foreach loop. It has two syntaxes:
1. The first syntax traverses the given array, and on each iteration, it assigns the key of the current element to the $key
variable and its value to the $value
variable, as demonstrated below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $array = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'); foreach ($array as $key => $value) { echo "{$key} => {$value}\n"; } /* Output: key1 => value1 key2 => value2 key3 => value3 */ ?> |
2. The second syntax traverses the array and assigns the current element’s value to the $value
variable on each iteration. To print the key and value from an associative array using this syntax, you can iterate over the array containing all the keys of the array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $array = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'); $keys = array_keys($array); foreach ($keys as $value) { echo $value . " => " . $array[$value], PHP_EOL; } /* Output: key1: value1 key2: value2 key3: value3 */ ?> |
The list()
function can be used to assign a list of variables in one operation. If you have an array of arrays, you can unpack the nested array elements using list()
, as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $array = [ [1, 2, 3], [4, 5, 6], ]; foreach ($array as list($a, $b, $c)) { echo "[$a, $b, $c]\n"; } /* Output: [1, 2, 3] [4, 5, 6] */ ?> |
It is possible to iterate over multidimensional arrays using nested foreach
loops. Here’s a simple example for a two-dimensional array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php $array = [ [1, 2, 3], [4, 5], [6, 7, 8] ]; foreach ($array as $row) { foreach ($row as $val) { echo "$val "; } echo PHP_EOL; } /* Output: 1 2 3 4 5 6 7 8 */ ?> |
2. Using for
loop
Finally, you can iterate over the array using a regular for loop. The idea is to loop from the 0th index to the size of the array, and access its elements using the array’s manual access notation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $array = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'); $keys = array_keys($array); for ($i = 0; $i < sizeof($keys); $i++) { echo $keys[$i] . " => " . $array[$keys[$i]], PHP_EOL; } /* Output: key1 => value1 key2 => value2 key3 => value3 */ ?> |
That’s all there is to iterating over an associative array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)