Search code examples
phprating

Rating System | Display the ratings from a single variable


So, my question is very strait forward, I have a single variable, per say 4, and I need to translate it to some kind of rating, very simple ( it goes from 1 to 5 ) without half stars or anything.

I need to display a rating out of a number which goes from one to five, so if I have 1 I will have a star, if I have 5 I will have five stars. I can do a for loop and display the images, but I also need to show the empty ( not rated ) star. I don't need any functionality to it, so you cannot actually rate, just show the ratings.

So because anyone is asking what I've tried, I haven't tried anything because I don't know where to begin.

I could do this to show a number of stars based on the variable I have ( which is a number from 1 -> 5 ):

<?php

$ratings = 3;

for( $i = 1; $i <= $ratings; $i++)
echo '<img src="some_image.png" />';

?>

This would be it, but what should I do for the non-rated starts, how do I display the rest of the empty stars till five ?


Solution

  • you can do an nested for loop like so:

    $tranStars;
    
    for($i=0;$i<5;$i++){
      if($i==0){
        for($j=0;$j<$rating;$j++){
          echo "<img src='yourFullStars.png'/>";
          $tranStars=$j;
        }
        $i=$tranStars;
      }
      echo "<img src='yourEmptyStars.png'/>";
    }
    

    or you could do two separate for loops:

    for($i=0;$i<$rating;$i++){
      echo "<img src='yourFullStars.png'/>";
    }
    for($i=0;$i<5-$rating;$i++){
      echo "<img src='yourEmptyStars.png'/>";
    }
    

    ... or any number of things, really.