简体   繁体   中英

error in array_filter

I have an issue here with filter_array.

below is my 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM