【发布时间】:2012-03-20 14:50:25
【问题描述】:
如何从数组的计数中排除空值? 因为 count 在计数中总是包含 null 值!
【问题讨论】:
-
PHP 空值与 SQL 空值不同。您必须使用自己的
my_count()函数来解决此问题。
标签: php
如何从数组的计数中排除空值? 因为 count 在计数中总是包含 null 值!
【问题讨论】:
my_count() 函数来解决此问题。
标签: php
count(array_filter($array, function($x) {return !is_null($x); })
【讨论】:
itertools.ifilter ;)
count($array) - count(array_filter($array, 'is_null'))。最好使用内置而不是声明自己的匿名函数:-)
function count_nonnull($a) {
$total = 0;
foreach ($a as $elt) {
if (!is_null($elt)) {
$total++;
}
}
return $total;
}
【讨论】:
尝试使用foreach 循环。
foreach($array as $index=>$value) {
if($value === null) unset($array[$index]);
}
echo count($array);
或者如果你不想修改数组:
function myCount($arr) {
$count = 0;
foreach($arr as $index=>$value) {
if($value !== null) $count++;
}
return $count;
}
echo myCount($array);
【讨论】:
in 而不是 as。在第二个(可以说是更可取的)版本中,您不需要 $index=>。
// 最简单的方法
回声计数(array_filter($array));
instructions
【讨论】: