PHP array_count_values() Function

Quick summary: The PHP array_count_values() function counts all the values of an array.

PHP array_count_values() Syntax

array_count_values(array $array): array
PHP

PHP array_count_values() Basic examples

$array = ["apple", "banana", "apple", "orange"];
print_r(array_count_values($array));
PHP
Output:
Array ( [apple] => 2 [banana] => 1 [orange] => 1 )

Counts how many times each value appears in the array.

$numbers = [1, 2, 2, 3, 3, 3];
print_r(array_count_values($numbers));
PHP
Output:
Array ( [1] => 1 [2] => 2 [3] => 3 )

Works with integer values as well.

PHP array_count_values() Real-world usage

$votes = ["yes","no","yes","yes"];
$results = array_count_values($votes);
echo $results['yes'];
PHP
Output:
3

Count votes or occurrences in survey results.

PHP array_count_values() Edge cases

$array = [1, 2, 2, 3.5];
print_r(array_count_values($array));
PHP
Output:
Warning for non-int/string values

Only string and integer values are counted. Others generate warnings.

PHP array_count_values() Common mistakes

Using with multidimensional arrays

array_count_values() only works on flat arrays.

Incorrect
array_count_values([[1],[1]]);
Correct
array_count_values($flatArray);

Flatten the array before using this function.

PHP array_count_values() Frequently Asked Questions

What does array_count_values() do?

Counts occurrences of values in an array.

Use case?

Frequency analysis.

Supports all types?

Only strings and integers.

Common mistake?

Using with objects.

Return type?

Associative array.

Performance?

Fast.

Alternative?

Manual counting.

Handles duplicates?

Yes.

Safe?

Yes.

Case sensitive?

Yes.

Best practice?

Normalize values first.

Used in analytics?

Yes.

PHP array_count_values() Related PHP Functions