Home >Backend Development >PHP Tutorial >How to get the size of PHP array?
How to get the size of PHP array?
In PHP, to get the size of an array (that is, the number of elements in the array), you can use the built-in function count()
. count()
The function can return the number of elements in an array or object. Below we will show how to get the size of a PHP array through specific code examples.
First, we define an array containing different elements, and then use the count()
function to get its size:
<?php // 定义一个包含不同元素的数组 $fruits = array("apple", "banana", "orange", "grape"); // 获取数组大小 $size = count($fruits); // 输出数组大小 echo "数组大小为:".$size; ?>
In the above code, we first define An array $fruits
containing four fruit names is obtained. Next, we use the count()
function to get the size of the array $fruits
and save the result in the variable $size
. Finally, we output the size of the array through the echo
statement.
In addition, if you want to get the size of the associative array, you can also use the count()
function. The following is a sample code containing an associative array:
<?php // 定义一个关联数组 $students = array( "Alice" => 19, "Bob" => 21, "Cathy" => 20 ); // 获取关联数组大小 $size = count($students); // 输出关联数组大小 echo "关联数组大小为:".$size; ?>
In this code, we define an associative array $students
, which contains the names and ages of three students. Through the count()
function, we can get the size of the associative array $students
and output the result.
In general, in PHP, the size of an array can be easily obtained through the count()
function. Whether it is an index array or an associative array, this function can be used to achieve it. Hopefully the sample code in this article will help readers better understand how to get the size of a PHP array.
The above is the detailed content of How to get the size of PHP array?. For more information, please follow other related articles on the PHP Chinese website!