4

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 Answers 3

4

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) . '%';
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 and then use counts['apple']*100/count($array) to get percentage!
2

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
)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.