Home  >  Article  >  Backend Development  >  How to find the number of arrays in php

How to find the number of arrays in php

PHPz
PHPzOriginal
2023-04-27 09:01:421332browse

There are many ways to find the number of arrays in PHP. Here are some commonly used methods:

  1. count() function

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
  1. sizeof() function

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
  1. foreach loop

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++;
}
  1. array_count_values() function

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!

Statement:
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