Home > Backend Development > PHP Tutorial > How to get the number of elements in an array in PHP

How to get the number of elements in an array in PHP

黄舟
Release: 2023-03-07 11:40:01
Original
30614 people have browsed it

在 PHP 中,使用 count()函数对数组中的元素个数进行统计。

语法格式如下

int count(mixed array [,int mode])
Copy after login

count()函数的参数说明如下图所示:

How to get the number of elements in an array in PHP

例如,使用 count()函数统计数组元素的个数,示例代码如下:

<?php
header("Content-Type:text/html; charset=utf-8");
$array = array("PHP中文网","百度","搜狗","m.sbmmt.com");
echo count($array);   //统计组数元素的个数
?>
Copy after login

输出结果为:

How to get the number of elements in an array in PHP

下面的一个实例将图书的数据存放在数组中,使用 count()函数递归地统计数组中图书数量并输出,具体代码如下:

<?php
header("Content-Type:text/html; charset=utf-8");
$array = array("PHP"=>array("PHP中文网","中文网","百度"),
                "asp"=>array("ASP 经验技巧宝典")
);//声明一个二维数组
echo count($array,COUNT_RECURSIVE);//递归统计数组元素的个数
?>
Copy after login

输出结果为:

How to get the number of elements in an array in PHP

注意:在统计二维数组时,如果直接使用 count()函数只会显示到一维数组的个数,所以使用递归的当时来统计二维数组的个数!

【相关教程推荐】

1. 相关专题推荐:《php数组(Array)

2. 相关视频课程推荐: 《数组统计函数:count(),array_count_values()和array_unique()

The above is the detailed content of How to get the number of elements in an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template