如何计算 PHP 数组中的非空条目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4422889/
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 count non-empty entries in a PHP array?
提问by Damon
Consider:
考虑:
[name] => Array ( [1] => name#1
[2] => name#2
[3] => name#3
[4] => name#4
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
)
$name = $_POST['name']
I want the result to be 4
.
我希望结果是4
.
count ($name) = 9
count (isset($name)) = 1
count (!empty($name)) = 1
I would think that last one would accomplish what I need, but it is not (the empty entries are from unfilled inputs on the form).
我认为最后一个可以完成我所需要的,但事实并非如此(空条目来自表单上未填写的输入)。
回答by moeffju
You can use array_filterto only keep the values that are “truthy” in the array, like this:
您可以使用array_filter仅保留数组中“真实”的值,如下所示:
array_filter($array);
If you explicitly want only non-empty
, or if your filter function is more complex:
如果您明确只想要 non- empty
,或者您的过滤器功能更复杂:
array_filter($array, function($x) { return !empty($x); });
# function(){} only works in in php >5.3, otherwise use create_function
So, to count only non-empty items, the same way as if you called empty(item)
on each of them:
所以,只计算非空项目,就像你调用empty(item)
它们中的每一个一样:
count(array_filter($array, function($x) { return !empty($x); }));
回答by Matt Huggins
count(array_filter($name));
回答by jmz
Here's a simple calculation function:
下面是一个简单的计算函数:
function non_empty(array $a) {
return array_sum(array_map(function($b) {return empty($b) ? 0 : 1;}, $a));
}
This will preserve array indexes if your form handling function needs them, like when you're associating the third input on name to the third value of another input set, and there are empty inputs in between them.
如果您的表单处理函数需要它们,这将保留数组索引,例如当您将 name 上的第三个输入关联到另一个输入集的第三个值时,并且它们之间有空输入。