This is the trick, get the number of star in total, Calculate Rating in PHP
If you’re collecting user ratings (e.g., 1 to 5 stars) and want to calculate the average rating and total number of stars, here’s a simple PHP example:
Let’s assume users have submitted these ratings:
$ratings = [
1 => 220,
2 => 31,
3 => 44,
4 => 175,
5 => 3188
];
PHP Code to Calculate Total Stars and Average Rating:
$totalStars = 0;
$voters = array_sum($ratings);
foreach ($ratings as $stars => $votes)
{//This is the trick, get the number of starts in total, then
//divide them equally over the total nr of voters to get the average
$totalStars += $stars * $votes;
}
Output:
printf(
‘%d voters awarded a total of %d stars to X, giving an average rating of %.1f’,
$voters,
$totalStars,
$totalStars/$voters
);