Home > Article > Backend Development > How to query the number of identical elements in an array in php
In PHP, we can easily query the number of identical elements in an array. In this article, we will introduce how to use PHP's built-in functions and custom functions to query the number of identical elements in an array.
Method 1: Use PHP built-in function array_count_values
The array_count_values function in PHP can count the number of occurrences of each element in an array. This function returns a new array where the keys are the values of the elements in the passed array and the values are the number of times that element appears in the array.
The following is an example:
$array = array("apple", "banana", "apple", "pear", "banana", "orange"); $count = array_count_values($array); print_r($count);
The output result is:
Array ( [apple] => 2 [banana] => 2 [pear] => 1 [orange] => 1 )
As can be seen from the output result, we successfully queried the number of the same elements in the array.
Method 2: Use a custom function
In addition to using PHP’s built-in function array_count_values, we can also write a custom function to query the number of the same elements in the array. The following is a simple custom function:
function count_same_elements($array) { $count = array(); foreach ($array as $value) { if (isset($count[$value])) { $count[$value]++; } else { $count[$value] = 1; } } return $count; }
The implementation principle of this function is similar to the array_count_values function. First, we create an empty array $count to store the number of occurrences of each element. We then iterate over the passed array $array and for each element in the array we check if the element is already present in the $count array. If it exists, we increment the element's count by one; otherwise, we add the element to the $count array and set the count to 1.
The following is how to use the custom function count_same_elements:
$array = array("apple", "banana", "apple", "pear", "banana", "orange"); $count = count_same_elements($array); print_r($count);
The output result is:
Array ( [apple] => 2 [banana] => 2 [pear] => 1 [orange] => 1 )
We can see that the output result of the custom function count_same_elements is the same as the array_count_values function.
Summary
In PHP, querying the number of identical elements in an array is a relatively common operation. We can use PHP's built-in function array_count_values, or we can write a custom function to achieve this function. Regardless of which method you use, you can easily query the number of identical elements in an array, allowing you to better handle array data.
The above is the detailed content of How to query the number of identical elements in an array in php. For more information, please follow other related articles on the PHP Chinese website!