Home > Article > Backend Development > How to find the number of arrays in php
There are many ways to find the number of arrays in PHP. Here are some commonly used methods:
count() function It is the most commonly used method in PHP and can be used to get the number of elements in an array.
The sample code is as follows:
$array = array('a', 'b', 'c', 'd', 'e'); $count = count($array); //5
The sizeof() function has the same function as the count() function and is used to obtain the contents of the array The number of elements, but in actual use, the count() function is generally used.
The sample code is as follows:
$array = array('a', 'b', 'c', 'd', 'e'); $size = sizeof($array); //5
Use the foreach loop to traverse the array, and you can count the number of elements in the array through a counter.
The sample code is as follows:
$array = array('a', 'b', 'c', 'd', 'e'); $count = 0; foreach($array as $item){ $count++; }
array_count_values() function is used to count the number of occurrences of each element in the array, and Return a new array.
The key of the new array is the value of the original array, and the value of the new array is the number of times the corresponding value appears in the original array.
The sample code is as follows:
$array = array('a', 'b', 'c', 'd', 'e', 'a', 'd', 'd'); $count_array = array_count_values($array); //array('a' => 2, 'b' => 1, 'c' => 1, 'd' => 3, 'e' => 1) $count = count($count_array); //5
In addition to the above methods, there are some other methods, such as: the alias count() of the sizeof() function, the count_recursive() function and the use of the array_keys() function Obtain the number of key names in the array, etc., but in actual use, one of the above methods is generally used to obtain the number of elements in the array.
The above is the detailed content of How to find the number of arrays in php. For more information, please follow other related articles on the PHP Chinese website!