What is PHP array_count_values() Function?
It counts the number of occurrence of each values in an array. Sometimes you want to know how many times each value exists in an array. In that case this function is very useful.
Syntax:
array_count_values(array)
Parameters:
The function has 1 parameter which is required-
array (Required): It is an array whose value the function counts.
Return Values:
The function returns an associative array whose keys are he values of the input array and values are the number of occurrence of each value of that input array.
Examples:
Example 1:
<pre>
<?php
$array = [1, 2, 3, 4, 1, 2, 3, 3];
print_r(array_count_values($array));
?>
</pre>
Output:
Array
(
[1] => 2
[2] => 2
[3] => 3
[4] => 1
)
Example 2:
<pre>
<?php
$array = [1, "php", 1, 2, 2, "php"];
print_r(array_count_values($array));
?>
</pre>
Output:
Array(
[1] => 2
=> 2
[2] => 2
)
Example 3:
<pre>
<?php
$array = ['one' => 1, 'two' => 1, 2, 3, 4, 2, 3, 3];
print_r(array_count_values($array));
?>
</pre>
Output:
Array(
[1] => 2
[2] => 2
[3] => 3
[4] => 1
)
Example 4:
<pre>
<?php
$array = ['php', 'php', 'PHP', 'mysql', 'mysql'];
print_r(array_count_values($array));
?>
</pre>
Output:
Array(
=> 2
[PHP] => 1
[mysql] => 2
)
Example 5:
<pre>
<?php
$array = [1, 1.5, "php", NULL];
print_r(array_count_values($array));
?>
</pre>
Output:
Warning: array_count_values(): Can only count string and integer values, entry skipped in D:\xampp\htdocs\array_coun_values.php on line 4
Warning: array_count_values(): Can only count string and integer values, entry skipped in D:\xampp\htdocs\array_coun_values.php on line 4
Array(
[1] => 1
=> 1
)
Explanation:
As there are two non-string or non-integer values (1.5 and NULL), the function throws two warnings.
Practical Usages of array_count_values() Function:
This function is used to get different statistical information, report generation, frequency analysis of array elements etc.
Notes on array_count_values() Function:
- To count the value occurrences, array keys are not relevant here. Check example 3.
- The function is case sensitive. So, the function considers “php” and “PHP” two different values. Check example 4.
Errors/ Exceptions:
The function throws an E_WARNING for every element of the array that is not either an integer or string. Check example 5.
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP array_count_values() Function
The PHP built-in array function array_count_values() makes it easy to count number of occurrence of each of the values in an array.
Reference:
https://www.php.net/manual/en/function.array-count-values.php