Introduction to the usage of count function in PHP array (with code)

不言
Release: 2023-04-05 15:24:01
forward
3277 people have browsed it

This article brings you an introduction to the usage of the count function in PHP arrays (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

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.
Syntax:
int count(mixed var [, int mode]) Returns 1 if var is an ordinary variable that is not an array, and 0 for non-existent, uninitialized, or empty arrays.
Optional parameter mode is set to COUNT_RECURSIVE (or 1), count() will recursively count the array, 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 
?>
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:

<?php 
$arr_age = array(18, 20, 25); 
$count = count($arr_age); 
for($i=1;$i<=$count;$i++){ 
  echo "第 $i 次循环"; 
} 
?>
Copy after login

This way you don’t have to perform count() calculations every time you loop, of course this is not necessary.

The above is the detailed content of Introduction to the usage of count function in PHP array (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!