st4ck0v3rfl0w
st4ck0v3rfl0w

Reputation: 6755

PHP: Count-IF for Arrays

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%)

Upvotes: 4

Views: 15730

Answers (3)

apis17
apis17

Reputation: 2855

$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);

Upvotes: 0

cletus
cletus

Reputation: 625057

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
)

Upvotes: 2

deceze
deceze

Reputation: 522075

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) . '%';
}

Upvotes: 4

Related Questions