2010-11-05 77 views
5
Array 
    (
     [0] => 'hello' 
     [1] => 'there' 
     [2] => 
     [3] => 
     [4] => 3 
    ) 

// how to get the number 5? 
+0

我一直在寻找我自己的代码错了,这使我觉得算忽略空值。 – Mohammad 2010-11-05 14:05:45

回答

20

的所有功能结果

$arr = Array 
    (
     0 => 'hello', 
     1 => 'there', 
     2 => null, 
     3 => null, 
     4 => 3, 
    ); 
var_dump(count($arr)); 

输出:

INT(5)

+2

'count(array_keys($ arr))'那么也许呢? – 2010-11-05 13:51:25

+3

在示例中,即使键(2,3)为空,计数仍然会计数它们,因为它们存在。 'count($ arr)'即使存在'false','null','0','''''等等,只要它们存在'count()'就会把它们加起来,正如'MatTheCat'所说的''echo count(array(1,null,null));'给出3 – RobertPitt 2010-11-05 13:56:01

2

对我的作品W/NULL

$array = array('hello', 'there', NULL, NULL, 3); 

echo "<pre>".print_r($array, true)."</pre><br />"; 
echo "Count: ".count($array)."<br />"; 

输出

Array 
(
    [0] => hello 
    [1] => there 
    [2] => 
    [3] => 
    [4] => 3 
) 

Count: 5 

快速Google search for PHP Array应拉起提供

0
下面

代码用PHP 5.3.2测试。输出为int 5

$a = array(
    0 => 'hello', 
    1 => 'there', 
    2 => null, 
    3 => null, 
    4 => 3, 
); 

var_dump(count($a)); 

您能否提供更多关于null的信息吗?旧版本可能?或者干脆与我们其他人混淆? :)

编辑:很好,贴错代码:)

+0

我猜他(??)误解了文档 – teemitzitrone 2010-11-05 13:57:54

0
echo count($array);