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
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.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myArr = array("Cycle", "Bike", "Bike", "Bike", "Car", "Car", "Car"); //Count all the values in array $newArr = array_count_values($myArr); //Print result print_r($newArr); ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myArr = array(6, 8, 2, 8, 8, 6, 2); //Find frequency of numeric elements in an array $newArr = array_count_values($myArr); //Print result print_r($newArr); ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myArr = array(6, "Cycle", "Bike", "Bike", 8, 8, 6, 2); //Count frequency of all the elements in array $newArr = array_count_values($myArr); //Print result print_r($newArr); ?> |
Output
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