开发者

error in array_filter

I have an issue here with filter_array.

below is my开发者_StackOverflow社区 code:

$array = array("0","0","1");
function returnzero($d){

    if($d=='0'){
       return $d;
    }
}

$all_zeros = array_filter($array, "returnzero");
echo count($all_zeros);

I would like to filter out all values that none other than zero. Above is my code. However, the count result returned is always 0.

may I know what is my mistake?

Thanks.


See the documentation on array_filter

You need to be returning true or false, not the number... So your function becomes:

function returnzero($d) { return $d == 0; }


You need to check $d != 0 and it will return all the non-zero values. Trying to return 0 is the same as returning false, so it fails.


Function must returns TRUE.

    $array = array(0, 0, 1);
    function returnzero($d){

        if($d=='0'){
           return true;
        }
    }

    $all_zeros = array_filter($array, "returnzero");
    echo count ($all_zeros);


Modify the return value to reflect the purpose:

 function iszero($d) { return $d == '0'; }

 $all_zeros = array_filter($array, 'iszero');

Regards

rbo


The function you pass into array_filter() must return TRUE or FALSE to tell PHP whether the current value being checked matches what you're filtering for. You're returning the number that was passed in. Since you're checking for zeroes, you're returning zero, which PHP interprets as FALSE. You could rewrite the function as follows:

if ($d == 0) {
    return TRUE;
} else {
    return FALSE;
}

or more concisely

return ($d == 0);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜