Using PHP's array_count_values() Function to Count Value Occurrences
This article explains the PHP array_count_values() function, its syntax, parameters, return values, and provides clear code examples showing how to count the frequency of values in arrays, along with important usage notes and a brief conclusion.
PHP is a widely used scripting language for web development, command‑line interfaces, and embedded applications, known for its ease of use and efficiency.
In PHP, functions are reusable code blocks; a particularly useful one is array_count_values(), which counts how many times each value appears in an array.
Usage
The syntax of the function is: array_count_values(array $array): array The function accepts an array and returns an associative array where each key is a unique value from the input and each value is the count of occurrences.
Parameter Description
array : required. The array whose values are to be counted.
Return Value
An associative array mapping each unique value to its number of occurrences.
Examples
Example 1 demonstrates counting colors in an array:
$colors = array("red", "blue", "green", "blue", "yellow", "red", "green", "red");
$color_count = array_count_values($colors);
print_r($color_count);Output:
Array
(
[red] => 3
[blue] => 2
[green] => 2
[yellow] => 1
)Example 2 shows counting words in a sentence:
$text = "The quick brown fox jumps over the lazy dog";
$word_array = explode(" ", $text);
$word_count = array_count_values($word_array);
print_r($word_count);Output:
Array
(
[The] => 1
[quick] => 1
[brown] => 1
[fox] => 1
[jumps] => 1
[over] => 1
[the] => 1
[lazy] => 1
[dog] => 1
)Notes
The function is case‑insensitive, treating values with different cases as the same key.
It is type‑sensitive; string "2" is converted to integer 2 before counting.
If the argument is not an array, the function returns false.
Conclusion
The array_count_values() function provides a quick way to tally the frequency of each value in a PHP array, making it a valuable tool for developers working on web applications and other PHP projects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
