Skip to content

Instantly share code, notes, and snippets.

@rizkhal
Last active May 5, 2019 19:30
Show Gist options
  • Save rizkhal/b6ed89fb31bcc5ecc85b32218c003665 to your computer and use it in GitHub Desktop.
Save rizkhal/b6ed89fb31bcc5ecc85b32218c003665 to your computer and use it in GitHub Desktop.
Simple way to calculate stars ratings like ecomerce
<?php
// our php array for example, if you using data from database, make it
$array = [
252, 124, 40, 29, 1
];
// stars, 1 - 5
$star = [
5, 4, 3, 2, 1
];
// loop for multiplication stars and user rate
for($i=0; $i<count($array); $i++) {
$rating[] = $array[$i] * $star[$i];
}
// calculate
$data = array_sum($rating) / array_sum($array);
// get 2 value after coma using php function round
$result = round($data, 2);
// display result
print_r($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment