Home > Article > Backend Development > How to see how many elements an array has in php
In PHP, we can use the count() function to count the number of elements in an array. The usage of the count() function is as follows:
Syntax:
count(array,mode)
Among them:
The following is a specific example code:
<?php // 定义一个一维数组 $arr1 = array(1, 2, 3); // 定义一个二维关联数组 $arr2 = array( 'name' => '张三', 'age' => 25, 'info' => array( 'phone' => '133xxxxxxxx', 'address' => '上海市浦东新区', ), ); // 统计一维数组元素个数 echo 'arr1 元素个数为:' . count($arr1) . '<br>'; // 统计多维数组元素个数,只统计第一层元素个数 echo 'arr2(mode=0)元素个数为:' . count($arr2) . '<br>'; // 统计多维数组元素个数,递归统计所有元素个数(包括多维数组) echo 'arr2(mode=1)元素个数为:' . count($arr2, 1) . '<br>'; // 统计多维数组元素个数,递归统计所有元素个数,并加上类型标识 echo 'arr2(mode=2)元素个数为:' . count($arr2, 2) . '<br>'; ?>
The output result is:
arr1 元素个数为:3 arr2(mode=0)元素个数为:3 arr2(mode=1)元素个数为:5 arr2(mode=2)元素个数为:array(3) { ["name"]=> int(1) ["age"]=> int(1) ["info"]=> int(2) }
It can be seen from the results that the count() function can flexibly meet our needs Various requirements for the number of array elements.
The above is the detailed content of How to see how many elements an array has in php. For more information, please follow other related articles on the PHP Chinese website!