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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_count_values(array $array): array

Parameters

ParameterDescription
array Values to count (strings or integers).

Return value

An array of counts keyed by value.

Examples

Count occurrencesTry it yourself
<?php
print_r(array_count_values(["php", "sql", "php", "css", "php"]));

Output

Array
(
    [php] => 3
    [sql] => 1
    [css] => 1
)
Most common wordsTry it yourself
<?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

VersionChange
PHP 4.0Added

Was this page helpful?