2

For example:

$array = [
    [
        'Item 1',
        'Item 2',
        [
            'Item 3',
            [
                'Item 4'
            ]
        ],
        'Item 5',
        [
            'Item 6'
        ]
    ]
];

What would be best way to, for example, loop through every item in the array, including sub-arrays, and echo them, producing Item 1Item 2Item 3Item 4Item 5?

I'm aware that I include a foreach inside a foreach inside a foreach... But the reason I'm doing this is because I want to be able to store a theoretically infinite amount of sub-categories, and not limit it to however many foreaches I have.

3
  • 2
    Check array_walk_recursive()
    – Sam
    Jan 9, 2014 at 21:40
  • 1
    recursion is the programmers friend.
    – aebersold
    Jan 9, 2014 at 21:45
  • recursion is the programmers friend friend friend friend ... :-)\
    – user557846
    Jan 9, 2014 at 21:47

2 Answers 2

3

This would best be handled by a recursive function rather than a straight loop. For example:

    function printArray($arr){
        foreach($arr as $val){
            if(is_array($val)){
               printArray($val);
            }
            else{
               echo $val;
            }
        }
    }
0
function items($arr)
{
    foreach($arr as $value)
    {
        if(!is_array($value)) echo $value."\n";
        if(is_array($value)) items($value);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.