开发者

Is there a function that will recursively traverse the values of an array?

I have an array that may have some null or blank values in it. Is there a PHP function that I can use to traverse this array to simply find out if there is a value anywhere?

For example:

[0]=>
[1]=>
[2]=> test

I'd like to test against the total number of values present, if any. count() won't work because this is only a portion of this array and it always returns 1 which is not accurate.

Array
(
    [inputbox] => Array
        (
            [name] => Array
                (
                    [0] => New Text Document.txt  <------- This is what I need to test
                    [1] => 
                )

      开发者_StackOverflow      [type] => Array
                (
                    [0] => text/plain
                )

            [tmp_name] => Array
                (
                    [0] => /var/tmp/phpLg2rFl
                    [1] => 
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 
                )

            [size] => Array
                (
                    [0] => 0
                    [1] => 
                )
        )
)


I don't understand your question very well, but perhaps you're looking for array_filter()?

array_filter($arr) will return an array with all empty values removed, so in your case only the index 2 with the value of test will be preserved, you could use count() afterwards.


In light of your comment:

if (count(array_filter($arr)) > 0)
{
    echo '$arr has values';
}

Beware that if you don't provide the second argument for array_filter() all values that can be converted to false will be dropped, such as 0's. If you want to remove only empty values you can do:

if (count(array_filter($arr, 'isset')) > 0)
{
    echo '$arr has values';
}

Or (my preferred version):

if (count(array_filter($arr, 'strlen')) > 0)
{
    echo '$arr has values';
}

You may also be interested in a Coalesce function for PHP.


In light of your last comment I still think array_filter() works, (assuming $_FILES) try this:

if (count(array_filter($_FILES['inputbox']['name'], 'strlen')) > 0)
{
    echo count($_FILES['inputbox']['name']) . ' files';
    echo '<br />';
    echo count(array_filter($_FILES['inputbox']['name'], 'strlen')) . ' files set';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜