PHP array_count_values() Function

Last Updated on August 10, 2021 by Roshan Parihar

PHP array_count_values() Function is used to count all the values for the number of times it occurs in an array. It calculated the frequency of all the elements present in the given array.

Let’s find out the use of the array_count_values() with the examples given below.

Syntax of PHP array_count_values() Function

array_count_values(array)

The function takes a single argument as the array or the array variable to get the frequency of the elements.

Description of Parameters

Name Description
array Required. It is the array that you have to use and find frequent the element is present.

Let’s understand the use of the PHP array_count_values() Function in PHP with the example given below.

Examples of PHP array_count_values() Function

See the different examples to learn the use of the array_count_values() Function in PHP.

Example 1: Count all the String Values in an Array

Suppose that, you have an array of string elements and you have to count all the string values in an array. The array_count_values() Function counts the number of occurrences of the same element in an array.

Output

Array ( [Cycle] => 1 [Bike] => 3 [Car] => 3 )

The above example contains string elements with the same elements that come for more than a single time. The function calculates the number of occurrences of the same element in the output.

Example 2: Find Frequency of Numeric Elements in an Array

Similarly, if you have all the numeric elements in an array, you can find the frequency of the numeric elements using the PHP array_count_values() function.

Output

Array ( [6] => 2 [8] => 3 [2] => 2 )

The above output shows the frequency of the numeric elements in an array.

Example 3: Combination of Integer and String Elements to Count Frequency

In addition to the above examples, you can also count the frequency of values in an array that contains a combination of string and integer elements.

Output

Array ( [6] => 2 [Cycle] => 1 [Bike] => 2 [8] => 2 [2] => 1 )

The above example shows the output that contains the calculated number of both numeric and string elements in an array.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.