W3docs

PHP foreach with Nested Array?

To loop through a nested array in PHP using a foreach loop, you can use nested foreach loops.

To loop through a nested array in PHP using a foreach loop, you can use nested foreach loops. The outer loop iterates through the top-level array, and the inner loop iterates through the sub-arrays. Here is an example:

Example of using nested foreach loops in PHP

<?php

$nestedArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

foreach ($nestedArray as $subArray) {
    foreach ($subArray as $element) {
        echo $element . "\n";
    }
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This will output:


1
2
3
4
5
6
7
8
9

You can use nested foreach to loop over more than 2 level nested arrays as well.