How to loop through a multidimensional array in PHP

Summary:

We recommend using the foreach loop if you need to iterate through a multidimensional PHP array. If you have a nested loop with an unknown amount of children, consider creating a recursive function that calls itself until complete.

Introduction

How to loop through a multidimensional array in PHP?

Arrays are iterable data structures meaning that an iterator or a loop can access its elements. Loops are central to any programming language, and PHP also has several different loops. The foreach loop is quite famous for associative arrays in PHP.

The foreach references keys and values as it loops through an associative array. It also relieves a programmer of the possibility of running over the array out of bounds error, thrown when an index exceeds the array’s limit.

loop through a multidimensional array in PHP

Besides foreach, PHP has for, while, and do-while loops. This article answers how to loop through a multidimensional array in PHP, and thus it will focus on the foreach loop. Nevertheless, you can read an in-depth article about the loops in PHP

Look Through PHP Multidimensional Arrays Using the foreach loop 

Let’s review the syntax of the foreach loop through an example.

$arr = array("Language"=>"PHP","Framework"=>"Laravel","CMS"=>"Wordpress");
 
foreach($arr as $key=>$value) {
    echo $key.' is '.$value.PHP_EOL;
}
 
/*
OUTPUT
Language is PHP
Framework is Laravel
CMS is WordPress
*/
 
?>

The array has three key/value entries. The foreach loop accesses them by keeping a reference two both as it loops through the array. The array in the example is linear, but what if it is multidimensional? How does that affect the foreach loop? Let’s see that next.

Can we use the foreach loop for multidimensional arrays in PHP?

A multidimensional array has nested levels of arrays. The foreach loop nesting is directly related to nesting in a multidimensional array. A three-dimensional array would require two nested loops. Note that the code complexity increases as the loop nesting increases. So, a foreach loop is helpful if the maximum level of a multidimensional array is known beforehand.

Generally, using more than two nested loops is not a good practice. So, it is always better to resort to recursive algorithms for more arrays that are more complex and inconsistent in terms of structure and complexity.

Example: How to print a multidimensional array in PHP using for loop

Here’s an example of the foreach loop. Let’s take a three-dimensional associative array in PHP.

$arr = [
    ['A', ['B', 'C']],
    ['D', ['E', 'F']],
    ['G', ['H', 'I']],
    ['J', ['K', 'L']],
    ['M', ['N', 'O']],
    ['P', ['Q', 'R']],
    ['S', ['T', 'U']],
    ['V', ['W','X']],
    ['Y', ['Z']]
];

Because the associative array is 3D, there’ll be three foreach loops. Two out of three will be nested.

/Access the first level of array. For instance, ['A',['B','C']]
foreach($arr as $subarray) {
   foreach($subarray as $value) {
      if(gettype($value) == 'array') {
         //Access the first level of array. For instance, ['B','C']
         foreach($value as $innermost) {
            echo ' '.$innermost.' ';
         }
      }
      else{
         echo ' '.$value.' ';
      }
     
   }
}

The outermost foreach loop accesses the elements on the same level of [‘A’, [‘B, ‘C’]]. The second loop accesses elements inside the [‘A’, [‘B, ‘C’]]. The second loops check if the element is an array and loops through it if true. So it iterates the arrays on the same level as [‘B’, ‘C’].

Here’s the output.

A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z

Recursive loop through multidimensional PHP array

As mentioned already, recursive algorithms are not concerned with the complexity of a multidimensional array, making them more robust and practical in actual scenarios. A recursive algorithm repeatedly calls itself. That’s why a recursive loop does not require nested loops to loop through a multidimensional array in PHP.

Here’s a recursive variant of the previous example.

function recursive_print($arr) {
   foreach($arr as $v) {
      if(gettype($v) == 'array') {
         recursive_print($v);
      }
      else{
         echo ' '.$v.' ';
      }
   }
}

The algorithm is robust enough to loop through any sort of multidimensional array. 

Example: create multidimensional PHP array in loop

There are other loops besides the foreach loop. For instance, the for-loop uses explicit counters and a boolean condition. The counters and conditions control how to loop through an associative array in PHP. Let’s see an example of a multidimensional array creation for loops.

for($i = 1; $i < 6; $i++) {
   // Stores the number and an empty array for its multiples
   $arr[$i-1] = [$i, []];
   for($j = 1; $j < 11; $j++) {
      //Stores the multiple of $i to the nested array.
      array_push($arr[$i -1][1], $i * $j);
   }
}

The example here creates a multidimensional array as.

loop through a multidimensional array in PHP

Here’s the output.

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => 4
                    [4] => 5
                    [5] => 6
                    [6] => 7
                    [7] => 8
                    [8] => 9
                    [9] => 10
                )
 
        )
 
    [1] => Array
        (
            [0] => 2
            [1] => Array
                (
                    [0] => 2
                    [1] => 4
                    [2] => 6
                    [3] => 8
                    [4] => 10
                    [5] => 12
                    [6] => 14
                    [7] => 16
                    [8] => 18
                    [9] => 20
                )
 
        )
 
)

Looping through a multidimensional JSON array with PHP

Here’s a neat example to show you how to loop through a multidimensional JSON array in PHP. Let’s say you have a JSON array that has 2+ levels included in it. JSON is actually a string formation. You can’t loop through it directly, you must convert the JSON string to a PHP array. Loop through it and then convert it back to a JSON string.

Luckily, PHP has functions to make this simple. The first step is to use the json_decode to convert a JSON string to a PHP array. By default, the json_encode function converts the array into a standard object. But if you pass a true boolean as the second parameter in the function, it’ll convert it into an array.

Once you get it converted to an array, you can use any of the above methods to loop through it per normal. Once complete, you can use the json_encode function to convert it back into a JSON string.

If you want to dig deeper, check out our in-depth article on looping through multidimensional arrays in PHP.

Conclusion

This article explores how to loop through a multidimensional array in PHP. It reviews the loops in PHP and includes an example for the foreach loops. The article also contrasts the foreach nested loop and recursive algorithms. Finally, there is an example of a multidimensional array creation using for loop in PHP. We hope this article was fun. Stay tuned for more excellent content at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems