Multidimensional Arrays Nested to Unlimited Depth

I’m eventually looking for all nested arrays called “xyz”. Has anyone got any suggestions?

Sure. Building on the suggestions to use some iterators, you can do:

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($array),
    RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $key => $item) {
    if (is_array($item) && $key === 'xyz') {
        echo "Found xyz: ";
        var_dump($item);
    }
}

The important difference between the other answers and this being that the RecursiveIteratorIterator::SELF_FIRST flag is being employed to make the non-leaf (i.e. parent) items (i.e. arrays) visible when iterating.

You could also make use of a ParentIterator around the array iterator, rather than checking for arrays within the loop, to make the latter a little tidier.

Leave a Comment