php array_filter表示"False"值

ste*_*Kim 0 php arrays

我array_filter在php中使用:

$new_array = array_filter($updated, "check_if_value_is_null_or_false");

function check_if_value_is_null_or_false($val) {
    return !is_null($val);       
};
Run Code Online (Sandbox Code Playgroud)

我知道我可以is_null用来过滤掉任何null有价值的东西.

我还想为string添加一个条件"False"作为值.

我该如何修改上述内容?

Tha*_*you 8

那么你可以自己做回调

function is_not_null_or_false($value) {
  return !(is_null($value) || $value === false);
}

array_filter($updated, 'is_not_null_or_false');
Run Code Online (Sandbox Code Playgroud)

或者您可以跳过单独的功能并执行

array_filter($updated, function($x) { return !(is_null($x) || $x === false); });
Run Code Online (Sandbox Code Playgroud)

编辑

看来你正在寻找字符串 "False"而不是布尔值

array_filter($updated, function($x) { return !(is_null($x) || $x === "False"); });
Run Code Online (Sandbox Code Playgroud)

编辑2

为了便于阅读,我们改变了

!is_null($x) && $x !== "False"
Run Code Online (Sandbox Code Playgroud)

至

!(is_null($x) || $x === "False")
Run Code Online (Sandbox Code Playgroud)

根据De Morgan的定律,这些是等价的,但第二个可能读得更好,特别是考虑到函数的名称.