Foreach loop through multidimensional array in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP nested loop

You can use the foreach loop in combination with the for loop to access all the keys, elements or values inside a PHP multidimensional array.

  • <?php
  • // Multidimensional array
  • $superheroes = array(
  •     "spider-man" => array(
  •         "name" => "Peter Parker",
  •         "email" => "peterparker@mail.com",
  •     ),
  •     "super-man" => array(
  •         "name" => "Clark Kent",
  •         "email" => "clarkkent@mail.com",
  •     ),
  •     "iron-man" => array(
  •         "name" => "Harry Potter",
  •         "email" => "harrypotter@mail.com",
  •     )
  • );
  •  
  • // 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>";
  • }
  • ?>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.