PHP array_count_values() Function

In this tutorial, we will explore how to use the array_count_values() function to count all the values of a given array.

PHP array_count_values() Function

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.

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:

  1. 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);

Resulting output:

    [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.


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.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.