Home > other >  How to filter zero in array php?
How to filter zero in array php?

Time:09-05

I tried get count zero in array with array_filter, my code is:

$arr=[1,2,0,3,4,5,0];
$countzero=count(
    array_filter($arr,function($x){
    if($x==0){
        return $x;
    }})
);

echo $countzero;

result is

0

expected result is

2

if condition if($x>0), result is 5, but why if($x==0) result is 0 ?, thanks for help

CodePudding user response:

You can do this a different way:

echo array_count_values($arr)[0];

https://www.php.net/manual/en/function.array-count-values.php

Demo: https://3v4l.org/Rq3qN

The issue with current implementation is that 0 is FALSE so:

If the callback function returns true, the current value from array is returned into the result array.

Could do:

$arr=[1,2,0,3,4,5,0];
$countzero=count(
    array_filter($arr,function($x){
    if($x==0){
        return 1;
    }})
);
echo $countzero;

which gives a TRUE for each $x==0.

CodePudding user response:

With php 7.4, you can write it more concisely:

$countzero = count(array_filter($arr, fn($x) => $x));

Indeed, array_filter() expects a callback which returns a boolean. And since 0 is converted to false and any other integer is converted to true, it will give the expected result.

  •  Tags:  
  • php
  • Related