count — 统计变量中的单元数目
count
(PHP 3, PHP 4, PHP 5)
count — 统计变量中的单元数目
说明
int count ( mixed var [, int mode] )
返回 var 中的单元数目,通常是一个 array(任何其它类型都只有一个单元)。
如果 var 不是数组类型,将返回 1(例外:count(NULL) 的结果是 0)。
注: 可选的 mode 参数自 PHP 4.2.0 起可用。
如果可选的 mode 参数设为 COUNT_RECURSIVE(或 1),count() 将递归地对数组计数。对计算多维数组的所有单元尤其有用。mode 的默认值是 0。
注意:
count() 对没有初始化的变量返回 0,但对于空的数组也会返回 0。用 isset() 来测试变量是否已经初始化。
请参考手册中数组一节中关于怎样在 PHP 中实现和使用数组的详细解释。
例子 1. count() 例子
$ a[ 0 ] = 1;
$ a[ 1 ] = 3;
$ a[ 2 ] = 5;
$ result = count ( $ a);
// $result == 3
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count ($b);
// $result == 3;
?>
例子 2. count() 的递归例子(PHP >= 4.2.0)
<?php
$food = array( 'fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard','pea'));
// recursive count
echo count($food,COUNT_RECURSIVE); // output 8
// normal count
echo count($food); // output 2
?>
注: sizeof() 函数是 count() 的别名。
参见 is_array(),isset() 和 strlen()。