有没有更好的方法从数组中过滤 NULL、false 和空字符串(并保留零)?

Is there a better way to filter NULL,false and empty strings from an array (and leave ZERO)?

我想从数组中过滤 NULL、false 和空字符串,但不过滤零值。那是我的代码,但它根本不起作用:

$array = array(1,2,3, "Test", NULL, 0, '', false);
$result = array();
foreach($array as $key=>$value){
    if(!empty($value) && !is_null($value) && false !== $value){
        $result[] = $value;
    }

}

print_r($result);

输出应该是

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => Test
    [5] => 0
)

有什么想法吗?

您可以使用 php 内置函数 array_filter() 和 strlen() 来解决这个问题。 php.net 上也有一个很好的参考:

$array = array(1,2,3, "Test", NULL, 0, '', false);
$result = array_filter($array, 'strlen');
print_r($result);

对我来说结果是:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => Test
    [5] => 0
)

这应该有所帮助。