array_count_values() Function in PHP

The array_count_values() function counts how many times each value appears in an array. It returns an associative array where the keys are the original values and the values are their occurrence counts.

Version Support: array_count_values() in PHP 8.5, array_count_values() in PHP 8.4, array_count_values() in PHP 8.3, array_count_values() in PHP 8.2, array_count_values() in PHP 8.1, array_count_values() in PHP 7.1, array_count_values() in PHP 7.2, array_count_values() in PHP 7.3, array_count_values() in PHP 7.4

Syntax

array_count_values(array $array): array

Example

<?php
$fruits = ["apple", "banana", "apple", "orange", "banana", "apple"];

$counts = array_count_values($fruits);

print_r($counts);
?>

Output:

Array
(
   [apple] => 3
   [banana] => 2
   [orange] => 1
)

Important note

The function counts only strings and integers. If the array contains other types of values, PHP may issue a warning and ignore those values.

<?php
$items = ["red", 5, "red", true, 5];

print_r(array_count_values($items));
?>

Here, the string "red" and integer 5 are counted; the boolean value is ignored.

Common use

Use array_count_values() to count repeated answers, words, categories, or other values in a list.

10 Views