Home > php教程 > php手册 > In-depth understanding of the count function of PHP arrays, in-depth understanding of count

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

WBOY
Release: 2016-07-06 14:24:41
Original
1160 people have browsed it

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;>
Copy after login

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;>
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template