In this tutorial, we will explore how to use the array_count_values() function to count all the values of a given array.
An array in PHP is a data structure that stores a collection of values, such as numbers or strings, in a linear order. It can be created by using the array() constructor or by using square brackets  with comma-separated values inside.
In some cases, you may encounter a scenario where you need to determine the number of values in a given array. This is where the PHP
array_count_values() function comes into play.
The following is the syntax of the
array_count_values() parameter is PHP:
array_count_values(array $array): array
The function accepts only one parameter:
array- this refers to the input array whose values you wish to count.
Function Return Value
The function will return an associative array of the values from the input array as the keys and their count as the value.
Let us look at a basic example on how we can use this function to determine the count of values in a given input array.
$array = array("apple", "banana", "apple", "cherry", "banana", "apple"); $count = array_count_values($array); print_r($count);
Array ( [apple] => 3 [banana] => 2 [cherry] => 1 )
As you can see, the method returns an associative array where the key
"apple" has a value of 3 because
"apple" appears three times in
"banana" appears two times and
"cherry" appears once.
In this post, we learned how we can use the
array_count_values() method to determine the count for the values in a given array. This method is very useful when you need to determine how many times an element occurs in an array or checking for duplicate values.