DEV Community

Aaron Junker
Aaron Junker

Posted on

3 2

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay