Home > Backend Development > PHP Problem > How does a function in php return the length of an array?

How does a function in php return the length of an array?

PHPz
Release: 2023-04-18 09:57:08
Original
520 people have browsed it

PHP is a very popular language and many web developers use it to develop websites and applications. In PHP, array is an important data type that can contain a set of data and can be processed through many built-in functions. This article will introduce how to get the length of an array in PHP.

In PHP, the count() function is usually used to obtain the length of an array. This function can return the number of elements in an array. For example:

$fruits = array("apple", "banana", "orange");
echo count($fruits); // 输出 3
Copy after login

In the above example, we declared an array $fruits containing 3 elements, and then used the count() function to obtain its length, and the output was 3.

If you want to calculate the length of a multidimensional array, you can use the second parameter of the count() function to specify the depth. For example:

$zebras = array(
    array("name" => "A", "age" => 5),
    array("name" => "B", "age" => 6),
    array("name" => "C", "age" => 7)
);
echo count($zebras, COUNT_RECURSIVE); // 输出 6
Copy after login

In the above example, we declared an array $zebras containing 3 associative arrays, and then used the count() function to calculate its length, and the output was 6. Among them, the second parameter COUNT_RECURSIVE means calculating the total number of elements of the multi-dimensional array.

In addition to the count() function, you can also use the sizeof() function to obtain the length of the array. The functions of these two functions are the same. For example:

$books = array("PHP", "JavaScript", "HTML");
echo sizeof($books); // 输出 3
Copy after login

In short, it is very convenient to get the length of an array in PHP. You can use the built-in count() function or sizeof() function. You only need to pass the array as a parameter of the function.

The above is the detailed content of How does a function in php return the length of an array?. 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