tags:

views:

140

answers:

3

Hi All,

What would be the most efficient way of counting the number of times a value appears inside an array?

Example Array ('apple','apple','banana','banana','kiwi')

Ultimately I want a function to spit out the percentages for charting purposes (e.g. apple = 40%, banana = 40%, kiwi = 20%)

+3  A: 

Just put it through array_count_values. The percentages should be easy...

$countedArray = array_count_values($array);
$total = count($countedArray);

foreach ($countedArray as &$number) {
    $number = ($number * 100 / $total) . '%';
}
deceze
+1 and then use `counts['apple']*100/count($array)` to get percentage!
TheMachineCharmer
A: 

Use array_count_values():

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
cletus
A: 
$a = Array ('apple','apple','banana','banana','kiwi');
$b = array_count_values($a);
function get_percentage($b,$a){
    $a_count = count($a);
    foreach ($b as $k => $v){
        $ret[$k] = $v/$a_count*100."%";
    }
    return $ret;
}
$c = get_percentage($b,$a);
print_r($c);
apis17