2

I have the following array:

[ratings] => Array
 (
      [0] => 3
      [1] => 3
      [2] => 2
      [3] => 3
      [4] => 3
      [5] => 1
      [6] => 3
      [7] => 4
      [8] => 5
 )

What would be the best and fastest way to get the the percentage of each rating. For example there are 9 ratings now, and 5 ratings of "3", so the percentage of rating "3" is 55.55%.

2
  • 4
    array_count_values() and count() thats 90% of the work - go do the rest.
    – user557846
    Oct 25, 2012 at 20:42
  • Wow, didn't know about array_count_values(). Excelent function! Thanks.
    – Psyche
    Oct 25, 2012 at 20:43

6 Answers 6

5

although he probably has something already, this is what I came up with.

<?php
$array = array(3,3,2,3,3,1,3,4,5);

function array_avg($array, $round=1){
    $num = count($array);
    return array_map(
        function($val) use ($num,$round){
            return array('count'=>$val,'avg'=>round($val/$num*100, $round));
        },
        array_count_values($array));
}

$avgs = array_avg($array);

/*
 * You can access any average/count like:
 * echo "The count of 3 is: {$avgs[3]['count']}";
 * echo "The average of 3 is: {$avgs[3]['avg']}";
 */

echo '<pre>'.print_r($avgs,1).'</pre>';

Output:

Array
(
    [3] => Array
        (
            [count] => 5
            [avg] => 55.6
        )

    [2] => Array
        (
            [count] => 1
            [avg] => 11.1
        )

    [1] => Array
        (
            [count] => 1
            [avg] => 11.1
        )

    [4] => Array
        (
            [count] => 1
            [avg] => 11.1
        )

    [5] => Array
        (
            [count] => 1
            [avg] => 11.1
        )
)

http://codepad.viper-7.com/yD9CQm

2
  • would it be hard to modify the function in order to return the percentage, and the count? For example, for rating "3", the percentage is 55.6 and the count is 5.
    – Psyche
    Oct 25, 2012 at 21:45
  • @Psyche updated. now returns an array for each number with the count and avg. Oct 25, 2012 at 21:50
4
function findPercentage($r, $ratings){
    $arr = array_count_values($ratings);
    return $arr[$r]/count($ratings) * 100;
}
1
  • 4
    Could you provide some explanation for your code? You know this site is not really a coding contest, we try to help people here.
    – kapa
    Oct 25, 2012 at 21:55
1

As commented, you can make use of the array_count_values and process with count with a simple iteration.

In my code-example I wrap this into a function of it's own:

$ratings = [3,3,2,3,3,1,3,4,5];

$percentages = function($ratings) {
    $total = count($ratings);
    $percentages = [];
    foreach(array_count_values($ratings) as $value => $count) {
        $percentages[$value] = $count / $total;
    }
    return $percentages;    
};

print_r($percentages($ratings));

Output (Demo):

Array (
    [3] => 0.55555555555556
    [2] => 0.11111111111111
    [1] => 0.11111111111111
    [4] => 0.11111111111111
    [5] => 0.11111111111111
)

I hope this demonstrates it fairly well. And again (for the fun):

print_r($percentages(array_map('strval', $percentages($ratings))));

(array_count_values() can only count STRING and INTEGER values)

Output:

Array (
    [0.55555555555556] => 0.2
    [0.11111111111111] => 0.8
)
0

$avg = array_sum($a)/count($a)

in Javascript:

var a = [1,2,3,4,5,6]; 
var avg = a.reduce(function(a,b){ return a+b })/a.length;
2
  • 2
    ok, but where did the OP say anything about javascript? may as well give him the answer in Fortran
    – user557846
    Oct 25, 2012 at 20:57
  • thought it can be useful ... Yes I can give it in Pascal, C, C++, C#, Perl and even in SmallTalk and Assembeler for at least 20 processors and in SQL too :) no joke! do you think PHP solution is fine? If Yes vote up please, not down :)
    – Reflective
    Oct 25, 2012 at 21:10
0
// $ratings is your array

function findPercentage($r, $ratings){
$count = 0; // count number of particular ratings
    foreach ($ratings as $i){
        if ($i == $r) $count++;
}

return $count/count($ratings) * 100;

}

example:

echo findPercentages(3, $ratings);
-1
$rating = array(3, 3, 5, 5, 3, 4);

$value = 0;
foreach ($rating as $i) {
    $value += $i;
}
$percentage = $value / count($rating);

echo $percentage;

== UPDATE

I wrote small test:

$rating = array();

echo "create array".PHP_EOL;

for ($i = 0; $i < 100000; $i++) {
    $rating[] = rand(1, 5);
}


echo "foreach algorithm: ".PHP_EOL;
$time = microtime();

$value = 0;
foreach ($rating as $i) {
    $value += $i;
}
$percentage = $value / count($rating);


echo $percentage.PHP_EOL;
echo "time is ".(microtime() - $time).PHP_EOL;

echo "array_sum algorithm: ".PHP_EOL;
$time = microtime();

$avg = array_sum($rating)/count($rating);
echo "time is ".(microtime() - $time).PHP_EOL;   

and result:

create array
foreach algorithm: 
2.99924
time is 0.017117
array_sum algorithm: 
time is 0.002819

Answer: use algorithm that wrote user @Reflective, use function array_sum

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.