DEV Community

Aaron Junker
Aaron Junker

Posted on

Foreach loops on multidimensional arrays in PHP

Inspired by https://bit.ly/3psMXqD

If you have a multidimensional array you don’t have to procced it like this:

<?php
    $array = [
        ["AA", "AB", 
            ["ACA", "ACD"]
        ],
        ["BA", "BB", 
            ["BCA", "BCD"]
        ],
        ["CA", "CB", 
            ["CCA", "CCD"]
        ],
    ];

    foreach($array as $a){
        foreach($a as $b){
            if(is_array($b)){
                foreach($b as $c){
                    echo "$c ";
                }
            }else{
                echo "$b ";
            }
        }
    }
?>
Enter fullscreen mode Exit fullscreen mode

You can simply make it like this:

<?php
    $array = [
        ["AA", "AB", 
            ["ACA", "ACD"]
        ],
        ["BA", "BB", 
            ["BCA", "BCD"]
        ],
        ["CA", "CB", 
            ["CCA", "CCD"]
        ],
    ];

    foreach($array as list($a, $b, list($c, $d))) {
        echo "$a $b $c $d ";
    };
?>
Enter fullscreen mode Exit fullscreen mode

For every new dimension you just need to add a new dimension of the list() function.

Top comments (0)