2

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

5 Answers 5

2

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; }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

0

Modify the return value to reflect the purpose:

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

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

Regards

rbo

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.