(PHP 4, PHP 5, PHP 7, PHP 8)
count — 计算数组中的单元数目,或对象中的属性个数
统计出数组里的所有元素的数量,或者对象里的东西。
     对于对象,如果安装了 SPL,可以通过实现
     Countable 接口对 count()挂钩(hook)
     。该接口只有一个方法
     Countable::count(),此方法为 count()
     函数返回值。
    
关于 PHP 中如何实现和使用数组可以参考手册中数组章节中的详细描述。
value数组或者 Countable 对象。
mode
       如果可选的 mode 参数设为
     COUNT_RECURSIVE(或 1),count()
     将递归地对数组计数。对计算多维数组的所有单元尤其有用。
      
        count() 能检测递归来避免无限循环,但每次出现时会产生 E_WARNING 错误
        (如果 array 不止一次包含了自身)并返回大于预期的统计数字。
       
   返回 value 中的单元数目。
   
   如果参数既不是数组,也不是实现
     Countable 接口的对象,将返回
     1。
   有个例外:如果
     value 是 null 则结果是 0。
  
| 版本 | 说明 | 
|---|---|
| 8.0.0 | 当 value参数传入了无效的 countable 类型,
       count() 现在会抛出 TypeError。 | 
| 7.2.0 | 当 value参数传入了无效的 countable 类型,
       count() 现在会产生警告。 | 
示例 #1 count() 例子
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));
$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));
?>
以上例程会输出:
int(3) int(3)
示例 #2 count() 非 Countable|array 的例子 (这是个反例,请勿模仿)
<?php
$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));
var_dump(count(null));
var_dump(count(false));
?>
以上例程会输出:
int(3) int(0) int(1)
Output of the above example in PHP 7.2:
int(3) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 int(0) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 int(1)
以上例程在 PHP 8 中的输出:
int(3) Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12
示例 #3 递归 count() 例子
<?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
?>