Reputation: 6177
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.
Upvotes: 2
Views: 1162
Reputation: 360802
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);
Upvotes: 0
Reputation: 15204
Modify the return value to reflect the purpose:
function iszero($d) { return $d == '0'; }
$all_zeros = array_filter($array, 'iszero');
Regards
rbo
Upvotes: 0
Reputation: 21937
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);
Upvotes: 1
Reputation: 165271
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; }
Upvotes: 2
Reputation: 84180
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.
Upvotes: 1