Search code examples
phpjqueryrating

How to calculate star rating?


I have one product and i want to calculate 5 star rating on the basic like and dislike

for example product have

  • like = 200 // that means 200 user like that product
  • dislike =10 // that means 10 user dislike that particular product

Solution

  • Here's a simple PHP function:

    <?php
        function calculateStarRating($likes, $dislikes){ 
            $maxNumberOfStars = 5; // Define the maximum number of stars possible.
            $totalRating = $likes + $dislikes; // Calculate the total number of ratings.
            $likePercentageStars = ($likes / $totalRating) * $maxNumberOfStars;
            return $likePercentageStars;
        }
    ?>
    

    To call the function:

    <?php
        $likeCount = 190; 
        $dislikeCount =10; 
        $calculatedRating = calculateStarRating($likeCount, $dislikeCount); 
    ?>
    

    To use the calculated value in Javascript:

    <script>
        var rating = <?php echo $calculatedRating; ?>;
        alert(rating); // For testing purposes.
    </script>
    

    These would get you started.