简体   繁体   English

PHP 在 array_filter 中只返回 0

[英]PHP return only 0 in array_filter

I am trying to only return when the value in the array is only 0 .我试图只在数组中的值仅为0 Because array_filter automatically filter 0 , null , empty etc I need to use custom callback.因为array_filter自动过滤0nullempty等我需要使用自定义回调。

But get every return that is not null , empty但是得到每一个不为null返回, empty

the array is数组是

[
    (int) 0 => '0',
    (int) 1 => '-100',
    (int) 2 => '100'
]

function countBETrades($arr) {
    $arrBE = array_filter($arr, function($v){
        return $v !== false && !is_null($v) && ($v != '' || $v == '0');
    });
    
    return count($arrBE);
}

if you want only the number 0 to be counted, then you only need to check for it (using the triple = in order to force PHP to check the type, so null === 0 is false):如果您只想计算数字0 ,那么您只需要检查它(使用三元组=以强制 PHP 检查类型,因此null === 0为假):

function countBETrades($arr) {
    $arrBE = array_filter($arr, function($v){
        return $v === 0 || $v === '0';
    });
    
    return count($arrBE);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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