PHP 8 reference · Array Functions
PHP array_count_values() Function
Count how many times each value occurs in an array, returning value => count pairs.
PHP 8 Since 4.0
Syntax
array_count_values(array $array): array
Parameters
| Parameter | Description |
|---|---|
array |
Values to count (strings or integers). |
Return value
An array of counts keyed by value.
Examples
<?php
print_r(array_count_values(["php", "sql", "php", "css", "php"]));
Output
Array
(
[php] => 3
[sql] => 1
[css] => 1
)<?php
$words = str_word_count(strtolower("the cat and the hat and the bat"), 1);
$counts = array_count_values($words);
arsort($counts);
print_r(array_slice($counts, 0, 2));
Output
Array
(
[the] => 3
[and] => 2
)Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
Related
count()· Return the number of elements in an array or Countable object. With COUNT_RECURSIVE it also counts nested elements.array_unique()· Remove duplicate values from an array, keeping the first occurrence of each and its key.arsort()· Sort an array by value in descending order, keeping each key attached to its value. Great for leaderboards.- PHP Array Functions · tutorial
- PHP Arrays · tutorial