本文介绍了如何计算在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 is not. (the empty entries are from unfilled inputs on form)
推荐答案
您可以使用,只保留该数组中的非空值,如:
You can use array_filter to only keep the values that are non-empty in the array, like this:
array_filter($array);
或者,如果你的过滤功能较为复杂:
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
所以,只计算非空的:
So, to count only non-empty:
count(array_filter($array));
这篇关于如何计算在PHP数组非空条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!