In this article, we will discuss array_count_values() function & its usage in PHP, along with understanding its basic implementation through the illustrations.
The array_count_values() function is used to count all the values inside an array. In other words, we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array.
Syntax:
array array_count_values( $array )
Parameters: This function accepts a single parameter $array. This parameter is the array for which we need to calculate the count of values present in it.
Return Value: This function returns an associative array with key-value pairs in which keys are the elements of the array passed as parameters and values are the frequency of these elements in an array.
Example: PHP Program to count values in an array.
<?php // Array of subjects with 4 elements $array1 = [ "Python" , "c/cpp" , "php" , "java" ];
// Count values in an array print_r( array_count_values ( $array1 ));
?> |
Output:
Array ( [Python] => 1 => 1 => 1 => 1 )
Example 2: PHP program illustrating the total count for each individual element in an array.
<?php // Array of subjects with 8 elements $array1 = [
"Python" ,
"c/cpp" ,
"php" ,
"java" ,
"R programming" ,
"c/cpp" ,
"php" ,
"java" ,
]; // Count values in an array print_r( array_count_values ( $array1 ));
?> |
Output:
Array ( [Python] => 1 => 2 => 2 => 2 [R programming] => 1 )