Home > Article > Backend Development > In-depth understanding of the count function of PHP arrays, in-depth understanding of the count_PHP tutorial
count()
PHP count() function is used to count the number of cells in an array or the number of attributes in an object, and returns the number of cells in the array or the number of attributes in the object.
Grammar:
int count( mixed var [, int mode] ) Returns 1 if var is an ordinary variable that is not an array, or 0 for a non-existent, uninitialized, or empty array.
If the optional parameter mode is set to COUNT_RECURSIVE (or 1), count() will count the array recursively, which is especially useful for counting all cells of a multi-dimensional array, but count() does not recognize infinite recursion. The default value of mode is 0 .
Example:
<?php echo count($x); //输出:0 $a = 2; echo count($a); // 输出:1 $arr_age = array(18, 20, 25); echo count($arr_age); // 输出:3 ?>
sizeof() is the alias of this function.
In practical applications, some loop operations are often performed based on the size of the array. It is recommended to write count() outside the loop:
<?php $arr_age = array(18, 20, 25); $count = count($arr_age); for($i=1;$i<=$count;$i++){ echo "第 $i 次循环"; } ?>
This eliminates the need to perform count() calculations every time it loops, but of course this is not necessary.
The above article on in-depth understanding of the count function of PHP arrays is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support Bangkejia.