如何计算 PHP 数组中的非空条目? [英] How to count non-empty entries in a PHP array?
本文介绍了如何计算 PHP 数组中的非空条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑:
[name] => Array ( [1] => name#1
[2] => name#2
[3] => name#3
[4] => name#4
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
)
$name = $_POST['name']
我希望结果是 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).
推荐答案
您可以使用 array_filter 只保留数组中真实"的值,如下所示:
You can use array_filter to only keep the values that are "truthy" in the array, like this:
array_filter($array);
如果您明确只想要非空
,或者您的过滤器功能更复杂:
If you explicitly want only non-empty
, or if your filter function is more complex:
array_filter($array, function($x) { return !empty($x); });
# function(){} only works in in php >5.3, otherwise use create_function
所以,只计算非空项目,就像你在每个项目上调用 empty(item)
一样:
So, to count only non-empty items, the same way as if you called empty(item)
on each of them:
count(array_filter($array, function($x) { return !empty($x); }));
这篇关于如何计算 PHP 数组中的非空条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文