Home  >  Article  >  Backend Development  >  How to query the length of a multidimensional array in php

How to query the length of a multidimensional array in php

青灯夜游
青灯夜游Original
2021-05-27 18:54:371912browse

In PHP, you can use the count() function to query the length of a multi-dimensional array. This function can return the number of elements in the array. The syntax is "count(array,mode)"; when the value of the mode parameter is 1 When counting multidimensional arrays, count the number of all elements in the multidimensional array recursively.

How to query the length of a multidimensional array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

PHP obtains two-dimensional (multi-dimensional) Arrays of various lengths

<?php
$array_test = array(
	&#39;0&#39; => array(&#39;0&#39;=>"aa"),
	&#39;1&#39; => array(&#39;1&#39;=>"bb"),
);
$n1=count($array_test,0);//不计较多维数组,只取最外层数组下一层的长度,结果为2
$n2=count($array_test,1);//计较多维数组,只取最外层数组下下一层的长度,结果为2+2=4
//下面依此类推

echo ($n1."<br>");
echo ($n2);
?>

Output:

2
4

Description:

count() function returns the array The number of elements.

For objects, if you install the SPL extension, you can call the count function by implementing the Countable interface. The Countable interface has one and only one method, Countable::count(), which returns the return value of the count() function.

The syntax is as follows:

count(array,mode);
Parameters Description
array Required. Specifies the array to count.
mode Optional. Specifies the mode of the function. Possible values:
  • 0 - Default. Not counting all elements in a multidimensional array.
  • 1 - Recursively count the number of elements in an array (count all elements in a multidimensional array).

If the parameter mode is set to COUNT_RECURSIVE (or 1), count() will recursively calculate the array. Especially useful when calculating multi-dimensional arrays.

If the first parameter is not an array or an object that implements the Countable interface, the count function will return 1.

Note: The count function can detect recursion to avoid infinite loops, but will return an E_WARNING prompt when encountering infinite recursion or getting a value larger than expected.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to query the length of a multidimensional array 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