How to use array_count_values() Function In PHP
The array_count_values() function is a built-in PHP function that counts all the values of an array and returns an associative array where keys are the unique values from the input array and values are the counts.
Example: This example shows the use of the above-mentioned approach.
<?php
// Declare an array
$arr = [10, 15, 20, 15, 20, 12, 10];
// Count the frequency of array items
$freq = array_count_values($arr);
print_r($freq);
?>
Output
Array ( [10] => 2 [15] => 2 [20] => 2 [12] => 1 )
Explanation:
- $array is the array containing the elements.
- array_count_values($array) returns an associative array with the count of each element.
Count Frequency of an Array Item in PHP
Given an array containing some elements (array elements can be repeated), the task is to count the frequency of array items using PHP.
Below are the approaches to count the frequency of an array item in PHP:
Table of Content
- Using array_count_values() Function
- Using a Loop
- Using array_reduce() Function