- PHP从入门到精通(第5版)
- 明日科技
- 274字
- 2025-02-18 07:19:53
7.8 统计数组元素个数

在PHP中,使用count()函数对数组中的元素个数进行统计。
语法格式如下:
int count ( mixed array [, int mode])
count()函数的参数说明如表7.3所示。
表7.3 count()函数的参数说明

例如,使用count()函数统计数组元素的个数,实例代码如下:
<?php $array = array("PHP函数参考大全","PHP程序开发范例宝典","PHP网络编程自学手册","PHP5从入门到精通"); echo count($array); //统计数组元素的个数,输出结果为4 ?>
【例7.11】将图书的数据存放在数组中,使用count()函数递归地统计数组中图书数量并输出,实例代码如下:(实例位置:资源包\TM\sl\7\11)
<?php $array = array("php" => array("PHP函数参考大全","PHP程序开发范例宝典","PHP数据库系统开发完全手册"), "asp" => array("ASP经验技巧宝典") ); //声明一个二维数组 echo count($array,COUNT_RECURSIVE); //递归统计数组元素的个数 ?>
结果为:6
注意
在统计二维数组时,如果直接使用count()函数只会显示到一维数组的个数,所以使用递归的方式来统计二维数组的个数。