Php array count values
From w3cyberlearnings
Contents |
PHP function array_count_values
This function returns a new key as the input array value, and the number of occurrences of the input value as a new array value.
Syntax array_count_values
- array: array input
array_count_values(array);
Example 1
<?php $country = array('China', 'USA', 'China', 'China', 'Thailand', 'Vietnam', 'Vietnam', 'China'); $country_count = array_count_values($country); print_r($country_count); ?>
Output
Array ( [China] => 4 [USA] => 1 [Thailand] => 1 [Vietnam] => 2 )
Example 2
<?php $country = array('China', 'USA', 'China', 'China', 'Thailand', 'Vietnam', 'Vietnam', 'China'); $country_count = array_count_values($country); foreach($country_count as $country=>$score) { echo "{$country} hits {$score} " . ($score > 1 ? "times" : "time") . "<br/>"; } ?>
Output
China hits 4 times USA hits 1 time Thailand hits 1 time Vietnam hits 2 times
Related Links
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_ exists
- array_keys