Home  >  Article  >  Backend Development  >  In-depth understanding of the count function of PHP arrays, in-depth understanding of the count_PHP tutorial

In-depth understanding of the count function of PHP arrays, in-depth understanding of the count_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:49:41840browse

In-depth understanding of the count function of PHP arrays, in-depth understanding of count

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:

<&#63;php
echo count($x);      //输出:0
$a = 2;
echo count($a);      // 输出:1
$arr_age = array(18, 20, 25);
echo count($arr_age);    // 输出:3
&#63;>

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:

<&#63;php
$arr_age = array(18, 20, 25);
$count = count($arr_age);
for($i=1;$i<=$count;$i++){
  echo "第 $i 次循环";
}
&#63;>

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1136647.htmlTechArticleIn-depth understanding of the count function of PHP arrays, in-depth understanding of count count() PHP count() function is used to calculate arrays The number of cells or the number of attributes in the object returns the number of cells or pairs of the array...
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