Home  >  Article  >  Backend Development  >  How to see how many elements an array has in php

How to see how many elements an array has in php

PHPz
PHPzOriginal
2023-04-20 10:06:48724browse

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:

  • array: required, an array to count the number of elements;
  • mode: Optional, the mode to be counted can be 0, 1, or 2. The default is 0, which means only counting the number of elements in the first level of the multi-dimensional array. When mode is set to 1, all elements will be counted recursively, including all levels of multi-dimensional arrays. When mode is set to 1, a type (i.e. array, object) identifier will be added before the statistical results.

The following is a specific example code:

<?php
// 定义一个一维数组
$arr1 = array(1, 2, 3);

// 定义一个二维关联数组
$arr2 = array(
    &#39;name&#39; => '张三',
    '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!

Statement:
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