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
<?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

Similar Reads

Using array_count_values() Function

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....

Using a Loop

You can use a loop to manually count the frequency of each element in the array. This approach is more flexible and can be customized to fit specific needs....

Using array_reduce() Function

The array_reduce() function reduces the array to a single value using a callback function, making it a powerful tool for various array manipulations, including counting frequencies....