array_count_values
Counts how many times each value occurs.
Syntax
array_count_values(array $array): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | An array of strings or integers. |
Return value
arrayAn array of "value => count".
Examples
The frequency of values:
<?php
echo json_encode(array_count_values(['tea', 'coffee', 'tea', 'tea']));Output:
{"tea":3,"coffee":1}The most frequent value:
<?php
$votes = ['php', 'js', 'php', 'python', 'php'];
$counts = array_count_values($votes);
arsort($counts);
echo array_key_first($counts);Output:
phpNotes
The function works only with strings and integers; other types raise a warning.
See also
- array_unique — Removes duplicate values from an array.
- count — Returns the number of elements in an array.
Related recipes
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.