Home > Article > Backend Development > How to query the length of a multidimensional array in php
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.
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( '0' => array('0'=>"aa"), '1' => array('1'=>"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:
|
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!