2011-10-06 15 views
4

如果我只想得到非空值數在該數組中,如果我使用count()sizeof它也會得到空索引。如何獲得只有非空元素數php

在我的情況

我有這樣Array ([0] =>)

count陣列是1。但我想得到非空計數,在這種情況下,它應該是0,我該怎麼做,請幫助......................... ...

+0

只有'NULL'或''''(空字符串)和'FALSE'可以移除以及(基本上所有的東西[PHP中的'FALSE'](http://php.net/manual/en/types .comparisons.php))? – hakre

回答

8

簡單地使用array_filter()沒有回調

print_r(array_filter($entry)); 
9
$count = count(array_filter($array)); 

array_filter將刪除評估爲false任何條目,如null,人數0和空字符串。如果你想只null被刪除,你需要:

$count = count(array_filter($array,create_function('$a','return $a !== null;'))); 
1

像...

$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);