Calculate average of values

47 Views Asked by At

I'm building a rating system where users can cast votes between 1-5. I store the values in a PHP array like this:

array(
    '1' => 99,
    '2' => 11,
    '3' => 0,
    '4' => 8123,
    '5' => 522,
);

So, 522 people voted 5.

My question is, how do I calculate the total average of this when putting all the votes together? So we end up with one value like:

Total rating: 4.2

The total rating should never exceed 5. What's the algorithm for this?

1

There are 1 best solutions below

7
On BEST ANSWER

The average (arithmetic mean) is calculated by $$ \frac{ \left(1 \times 99\right) + \left(2 \times 11\right) + \left(3 \times 0\right) + \left(4\times 8123\right) + \left(5\times 522\right)}{99 + 11 + 0 + 8123 + 522} $$ which I calculate to be approximately $4.023$