从 PHP 数组中删除 NULL、FALSE 和 '' - 但不是 0 - [英] Remove NULL, FALSE, and '' - but not 0 - from a PHP array
本文介绍了从 PHP 数组中删除 NULL、FALSE 和 '' - 但不是 0 -的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除 NULL
、FALSE
和 ''
值.
I want to remove NULL
, FALSE
and ''
values .
我使用了 array_filter
但它也删除了 0
.
I used array_filter
but it removes the 0
' s also.
有什么功能可以做我想做的事吗?
Is there any function to do what I want?
array(NULL,FALSE,'',0,1) -> array(0,1)
推荐答案
array_filter
如果您使用 相同
比较运算符.
$values = [NULL, FALSE, '', 0, 1];
function myFilter($var){
return ($var !== NULL && $var !== FALSE && $var !== '');
}
$res = array_filter($values, 'myFilter');
或者如果不想定义过滤函数,也可以使用匿名函数(闭包):
Or if you don't want to define a filtering function, you can also use an anonymous function (closure):
$res = array_filter($values, function($value) {
return ($value !== null && $value !== false && $value !== '');
});
如果您只需要数值,您可以使用 is_numeric 作为您的回调:example
If you just need the numeric values you can use is_numeric as your callback: example
$res = array_filter($values, 'is_numeric');
这篇关于从 PHP 数组中删除 NULL、FALSE 和 '' - 但不是 0 -的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文