Jump to: navigation, search

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


Navigation
Web
SQL
MISC
References