PHP Tips and Tricks - Iterating Through Multidimensional Arrays

Guest Posts Paolo Nikko Nuñal

Dealing with arrays in PHP is a great thing since you can do wonders for your program. Considering the fact that arrays in PHP are powerful enough to hold temporary data and it is easy for you to traverse through them. In our past lessons before, we already knew how to traverse through multidimensional arrays but you might encounter some complicated arrays that you need to get the key as well as the value.

In this example you are going to learn how to traverse through a multi dimenstional array with different sets of list.

Example:

<?php
$animals = array(
           'Mammals' => array("Dog","Cat","Whale Shark","Monkeys"),
           'Birds' => array("Pigeons","Ostrich"),
           'Fish' => array("Catfish","Carp","Gold Fish","Tetra Barb")
           );
echo var_dump($animals);

?>


From the code above, we can iterate through the sets of array list by using a for loop within a for loop. This is most useful if you are planning on getting the set of keys as well as the values corresponding through that particular key.

foreach($animals as $family_name => $family_list){
         echo $family_name.": ";
      foreach($family_list as $set => $family_animal){
         echo $family_animal." ";
      }
  }


By iterating two for loops it will first read the 'Mammals' then its values, then go to 'Birds', then 'Fish'. The values will be: Mammals: Dog Cat Whale Shark Monkeys Birds: Pigeons Ostrich Fish: Catfish Carp Gold Fish Tetra Barb