tags:

views:

202

answers:

1

I have a multi dimensional array. The only actual values (other than other arrays) in there are numbers. By default, they are all 0.

I would like to know is there an easy way to determine if the array has a value other than 0 in it.

I know I could build something recursive, but I want to know if I could leverage array_map() or something similar. I could not get array_count_values() to work with an associate array.

If that's not possible, how would I design a recursive function?

Here are some test cases

$array = array(
'test' => array(0, 0, 0, array(0, 0, 0))
)

Should return false.

$array = array(
'test' => array(0, 0, 0, array(6, 0, 0)) // notice the 6
)

Should return true.

Thanks!

+3  A: 

Hm, I can't think of a way to use PHP's built-in functions to do the job. So here's a quick recursive solution:

function hasnonzero($array)
{
    foreach ($array as $value)
    {
        if (is_array($value))
        {
            if (hasnonzero($value))
                return true;
        }
        else if ($value != 0)
            return true;
    }

    return false;
}
John Kugelman
Thanks John!
alex