Foreach loop through multidimensional array in PHP. You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.
Let’s take a look at the following example to understand how it basically works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?php // Multidimensional array $superheroes = array( "spider-man" => array( "name" => "Peter Parker", ), "super-man" => array( "name" => "Clark Kent", ), "iron-man" => array( "name" => "Harry Potter", ) ); // Printing all the keys and values one by one $keys = array_keys($superheroes); for($i = 0; $i < count($superheroes); $i++) { echo $keys[$i] . "{<br>"; foreach($superheroes[$keys[$i]] as $key => $value) { echo $key . " : " . $value . "<br>"; } echo "}<br>"; } ?> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.