php 如何检查数组是否包含空元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6621683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if an array contains empty elements?
提问by Ryan
Let's make some examples:
让我们举一些例子:
array("Paul", "", "Daniel") // false
array("Paul", "Daniel") // true
array("","") // false
What's a neat way to work around this function?
解决此功能的巧妙方法是什么?
回答by Hyman Murdoch
回答by user187291
The answer depends on how you define "empty"
答案取决于你如何定义“空”
$contains_empty = count($array) != count(array_filter($array));
this checks for empty elements in the boolean sense. To check for empty strings or equivalents
$contains_empty = count($array) != count(array_filter($array, "strlen"));
To check for empty strings only (note the third parameter):
仅检查空字符串(注意第三个参数):
$contains_empty = in_array("", $array, true);
回答by Mohammed Abdallah
function has_empty(array $array)
{
return count($array) != count(array_diff($array, array('', null, array())));
}
回答by Hamid Seyyedi
$array = array("Paul", "", "Daniel")
if( $array != array_filter( $array ) )
return FALSE;
回答by SteeveDroz
function testEmpty($array) {
foreach ($array as $element) {
if ($element === '')
return false;
}
return true;
}
Please check out the comments down below for more information.
请查看下面的评论以获取更多信息。
回答by augsteyer
Since I do enjoy me some fancy anonymous functions here is my take on it. Not sure about performance, but here it is:
因为我确实喜欢我一些花哨的匿名函数,所以我对它的看法。不确定性能,但这里是:
$filter = array_filter(
["Paul", "", "Daniel"],
static function ($value) {
return empty($value); // can substitute for $value === '' or another check
}
);
return (bool) count($filter);
Logically explained. If anonymous returns true, it means that it found an empty value. Which means the filter array will contain only empty values at the end (if it has any).
逻辑解释。如果anonymous 返回true,则表示它找到了一个空值。这意味着过滤器数组最后将只包含空值(如果有的话)。
That's why the return checks if the filter array has values using count
function.
这就是为什么返回使用count
函数检查过滤器数组是否具有值的原因。
The (bool)
type cast is equivalent to return count($filter) === 0
.
该(bool)
类型转换相当于return count($filter) === 0
。
May you all find the happiness you seek.
祝大家都能找到自己想要的幸福。