0

in PHP, how can i loop an array of array without know if is or not an array?

Better with an example:

Array
(
    [0] => Array
        (
            [0] => big
            [1] => small
        )

    [1] => Array
        (
            [0] => big
            [1] => tiny
        )

    [2] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
            [4] => e
            [5] => f
        )
    [3] => row
    [4] => cols
    [5] => blablabla
    [6] => Array
        (
            [0] => asd
            [1] => qwe
        )
}

any idea? thanks.

0

5 Answers 5

4

Which approach to choose depends on what you want to do with the data.

array_walk_recursive [docs] lets you traverse an array of arrays recursively.

Sign up to request clarification or add additional context in comments.

Comments

4

You can use is_array to check if that element is an array, if it is, loop over it recursively.

Comments

1

You can use is_array to check if something is an array, and/or you can use is_object to check if it can be used within foreach:

foreach ($arr as $val)
{
    if (is_array($val) || is_object($val)) 
    {
        foreach ($val as $subval)
        {
            echo $subval;
        }
    }
    else
    {
        echo $val;
    }
}

Another alternative is to use a RecursiveIteratorIterator:

$it = new RecursiveIteratorIterator(
           new RecursiveArrayIterator($arr),
           RecursiveIteratorIterator::SELF_FIRST);

foreach($it as $value)
{
   # ... (each value)
}

The recursive iterator works for multiple levels in depth.

Comments

0
foreach( $array as $value ) {
    if( is_array( $value ) ) {
        foreach( $value as $innerValue ) {
            // do something
        }
    }
}

That would work if you know it will be a maximum of 2 levels of nested array. If you don't know how many levels of nesting then you will need to use recursion. Or you can use a function such as array_walk_recursive

Comments

0
$big_array = array(...);
function loopy($array)
{
    foreach($array as $element)
    {
        if(is_array($element))
        {
            // Keep looping -- IS AN ARRAY--
            loopy($element);
        }
        else
        {
            // Do something for this element --NOT AN ARRAY--
        }
    }
}

loopy();

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.