php.array_count_values()
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.
In this tutorial, we will explore how to use the array_count_values()
function to count all the values of a given array.
Function Syntax
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.
Examples
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);
Resulting output:
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 $array
. Similarly, "banana"
appears two times and "cherry"
appears once.
Conclusion
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.