phparraysforeach

Loop over an array of unknown depth


How to loop an array if the data is 1 level or more than 1 level?

I tried it with

foreach ($array['bGeneral'] as $item) {
    echo $item['bItem'];
}

but for arrays that have 1 level of data an error occurs.


Solution

  • Basically you need to check if the first element of $array['bGeneral'] is an array or a data value, and if so, process the data differently. You could try something like this:

    if (isset($array['bGeneral']['bItem'])) {
        // only one set of values
        $item = $array['bGeneral'];
        // process item
    }
    else {
        // array of items
        foreach ($array['bGeneral'] as $item) {
            // process item
        }
    }
    

    To avoid duplication of code, you will probably want to put the item processing code in a function.

    Alternatively you could create a multi-dimensional array when you only have one value and then continue processing as you do with multiple values:

    if (isset($array['bGeneral']['bItem'])) {
        $array['bGeneral'] = array($array['bGeneral']);
    }
    foreach ($array['bGeneral'] as $item) {
        // process item
    }