Home > Backend Development > PHP Tutorial > In-depth understanding of the count function of PHP arrays

In-depth understanding of the count function of PHP arrays

*文
Release: 2023-03-18 19:56:01
Original
1689 people have browsed it

This article provides an in-depth analysis of the count function of PHP arrays. To give you a reference, I hope it will be helpful to everyone.

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 an array The number of units or the number of attributes in the object.

Syntax:

int count(mixed var [, int mode]) If var is an ordinary variable that is not an array, it returns 1. If it does not exist, is not initialized, or An empty array returns 0.

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
?>
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 go through it every time Perform a count() calculation, although this is not required.

Related recommendations:

Analysis of similarities and differences between three methods of php array merging

Example of php array combination and deduplication

The most complete introduction to PHP arrays

The above is the detailed content of In-depth understanding of the count function of PHP arrays. For more information, please follow other related articles on the PHP Chinese website!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template