如果我只想得到非空值數在該數組中,如果我使用count()
或sizeof
它也會得到空索引。如何獲得只有非空元素數php
在我的情況
我有這樣Array ([0] =>)
的count
陣列是1
。但我想得到非空計數,在這種情況下,它應該是0
,我該怎麼做,請幫助......................... ...
如果我只想得到非空值數在該數組中,如果我使用count()
或sizeof
它也會得到空索引。如何獲得只有非空元素數php
在我的情況
我有這樣Array ([0] =>)
的count
陣列是1
。但我想得到非空計數,在這種情況下,它應該是0
,我該怎麼做,請幫助......................... ...
簡單地使用array_filter()沒有回調
print_r(array_filter($entry));
$count = count(array_filter($array));
array_filter
將刪除評估爲false
任何條目,如null
,人數0
和空字符串。如果你想只null
被刪除,你需要:
$count = count(array_filter($array,create_function('$a','return $a !== null;')));
雖然我不是用PHP好,我認爲你應該編程刪除空元素從陣列 the link might help
像...
$count=0;
foreach ($array as $k => $v)
{
if (!empty($v))
{
$count++;
}
}
應該做的伎倆。 你也可以把它包在像一個函數:
function countArray($array)
{
$count=0;
foreach ($array as $k => $v)
{
if (!empty($v))
{
$count++;
}
}
return $count;
}
echo countArray($array);
一種選擇是
echo "Count is ".count(array_filter($array_with_nulls, 'strlen'));
如果不計空的,你可以做到這一點
echo "Count is ".count(array_filter($array_with_nulls));
在空值這個博客你可以看到更多信息
http://briancray.com/2009/04/25/remove-null-values-php-arrays/
只有'NULL'或''''(空字符串)和'FALSE'可以移除以及(基本上所有的東西[PHP中的'FALSE'](http://php.net/manual/en/types .comparisons.php))? – hakre