Loop Through Multidimensional Arrays: PHP Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

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;
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.

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.' ';
         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') {
         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.

    [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.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources.

We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Looping through Multidimensional PHP Arrays

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.

Learn More About Loops in PHP

Want to learn how to use loops in PHP? This article is part of our series on looping through PHP arrays. Check out our full series to become a PHP array loop ninja.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.