views:

35

answers:

5

Dear all,

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.

+1  A: 

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.

Gazler
+2  A: 

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; }
ircmaxell
+1  A: 

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);
Alexander.Plutov
A: 

Modify the return value to reflect the purpose:

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

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

Regards

rbo

rubber boots
A: 

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);
Marc B