Categories
PHP Tips & Tutorials

PHP: Count the Number of Occurrences of Each Unique Value in an Array

For example, you have an array of non-unique values that are student names, you know there are just 5 of them but a total of 15 elements exist in that array with some student names repeated in more than one elements.

To count the occurrences of all the unique values, in this case, 5 student names, in that array, simply use the PHP function array_count_values():

$counts = array_count_values($students);

The resulted array looks like:

Array
(
    ['George'] => 3
    ['Clark'] => 2
    ['John'] => 4
    ['Annie'] => 1
    ['Betsy'] => 5
)

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.