PHP: count | 您所在的位置:网站首页 › php8中文手册 › PHP: count |
count
(PHP 4, PHP 5, PHP 7, PHP 8) count — 统计数组、Countable 对象中所有元素的数量 说明 count(Countable|array $value, int $mode = COUNT_NORMAL): int用于数组时,统计数组中元素的数量;用于实现了 Countable 接口的对象时,返回 Countable::count() 方法的返回值。 参数value 数组或者 Countable 对象。 mode如果可选的 mode 参数设为 COUNT_RECURSIVE(或 1),count() 将递归地对数组计数。对计算多维数组的所有单元尤其有用。 警告count() 能检测递归来避免无限循环,但每次出现时会产生 E_WARNING 错误 (如果 array 不止一次包含了自身)并返回大于预期的统计数字。 返回值返回 value 中的元素的数量。在 PHP 8.0.0 之前,如果参数既不是数组也不是实现了 Countable 接口的对象,将返回 1。当 value 为 null 时返回 0。 更新日志 版本 说明 8.0.0 当 value 参数传入了无效的 countable 类型, count() 现在会抛出 TypeError。 7.2.0 当 value 参数传入了无效的 countable 类型, count() 现在会产生警告。 示例
示例 #1 count() 例子 以上示例会输出: int(3) int(3)
示例 #2 count() 非 Countable|array 的例子 (这是个反例,请勿模仿) 以上示例会输出: 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() 例子 以上示例会输出: int(8) int(2)
示例 #4 Countable 对象 以上示例会输出: int(2) 参见is_array() - 检测变量是否是数组 isset() - 检测变量是否已声明并且其值不为 null empty() - 检查变量是否为空 strlen() - 获取字符串长度 is_countable() - Verify that the contents of a variable is a countable value Array 数组 |
CopyRight 2018-2019 实验室设备网 版权所有 |