Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_count_values() function

Reference for PHP array_count_values(): count how often each string or integer occurs in an array, sort by frequency, and what happens with other types.

array_count_values() builds a frequency table. It returns an array whose keys are the distinct values of the input and whose values are how many times each one occurred. The first occurrence decides the order of the keys.

Only strings and integers can be counted, because they are the only types that can be array keys. This makes it perfect for counting words, tags, votes or status codes.

PHP
<?php
print_r(array_count_values(["a", "b", "a"]));
// ["a" => 2, "b" => 1]

Try it

PHP Counting words and votes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Case, types and unsupported values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_count_values(array $array): array
Name Description
$array The array whose values are counted. Values should be strings or integers.

Return value: an array mapping each distinct value to its number of occurrences.

Warnings: each value that is neither a string nor an integer (floats, booleans, null, arrays, objects) is skipped and raises Warning: array_count_values(): Can only count string and integer values, entry skipped.

Usage notes

  • Comparison is by array key rules. The string "1" and the integer 1 are the same key, and the result key is the integer 1.
  • Case sensitive. Normalize with array_map('strtolower', ...) first if "PHP" and "php" should be one entry.
  • Order: keys appear in the order of first occurrence. Sort with arsort() for "most common first"; the sort is stable since PHP 8.0, so ties keep their first-seen order.
  • Counting by a field: extract the field first with array_column(), then count.
  • Not for floats or booleans. Convert them to strings yourself (for example (string) $value) if you need to count them.
  • Unique values only: if you only need the distinct list, array_unique() is enough.