How to calculate average rating out of 5 in php

In PHP, you can calculate the average rating out of 5 by collecting the individual ratings and then averaging them.

Let’s say you have an array of ratings:

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

To calculate the average, you can use the following code:

$totalRatings = count($ratings);   // Get the total number of ratings
$sumRatings = array_sum($ratings);   // Sum all the ratings
  
$averageRating = $sumRatings / $totalRatings;   // Calculate the average
  
echo "Average Rating: " . $averageRating;

This will output the average rating.

Let’s run through an example:

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

The total number of ratings is 5. The sum of all ratings is 18 (3 + 4 + 5 + 2 + 4).

So, the average rating would be 18 / 5 = 3.6.

Therefore, the output of the code would be:

Average Rating: 3.6

Leave a comment