How to query the number of arrays in php

PHPz
Release: 2023-05-07 17:49:11
Original
655 people have browsed it

In PHP, querying the number of elements in an array is a very common operation. Specifically, we can use PHP's built-in function count() to count the number of elements in an array.

The syntax of this function is as follows:

count(array $array, int $mode = COUNT_NORMAL) : int
Copy after login

The $array parameter represents the array in which the number of elements is to be counted, and the $mode parameter represents the statistical mode , optional parameter and the default value is COUNT_NORMAL, indicating normal mode. The return value is an integer representing the number of elements in the array.

For example, we define a sample array:

$exampleArray = array('apple', 'banana', 'cherry');
Copy after login

Then we can query the number of elements of the array through the count() function:

$count = count($exampleArray);
echo $count; // 输出 3
Copy after login

Another thing to note is that if what is passed in is not an array, but a variable of other types, the count() function will return 1. For example:

$count = count('hello');
echo $count; // 输出 1
Copy after login

The last thing to note is that if it is an associative array, you can also use the count() function to calculate the number of elements. For example:

$assocArray = array('name' => 'Tom', 'age' => 20, 'gender' => 'male');
$count = count($assocArray);
echo $count; // 输出 3
Copy after login

The $count value here is still 3, not 4, because the keys in the associative array are also counted as one of the elements of the array.

In short, it is a very simple and common operation to query the number of elements in an array through the PHP built-in function count(). When writing PHP programs, we can often use this function to count the number of elements in an array, so that we can better control the logic and running results of the program.

The above is the detailed content of How to query the number of arrays in php. For more information, please follow other related articles on the PHP Chinese website!

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