PHP | Show star rating (empty or filled stars)

|
| By Webner

Sometimes situation arises when we have to show the ratings on our site like user rating of all the products available on our site. Then we have to first get the rating from where we have it like sometimes it may be from the third party etc. Once we have the rating we can simply show it through this simple php, html and CSS code. We also need images of the stars – one filled and one empty.

For example, star images will be like:

Firstly, we will get the image path and will store it to pass in html. Then we will get the percentage of the rating. It can be done through:

<?php  
$rating=/*Get rating from where you stored it*/;
$img_url=/*'Star Image path'*/;
$rating_val = (round($rating,1)/ 5) * 100;
?>

Now, we have the percentage of rating out of 5 and also we have star images so we will present them through this HTML:

 <div class="ratingbox" style="background:url('<?php echo $img_url?>') repeat-x">
 <div style="width: <?php echo $rating_val; ?>%;background:url('<?php echo $img_url?>') repeat-x;" class="rating">
 </div>
 </div>

Here, we are setting the background of div to the stars image. Repeat-x is very important here because we will need to repeat the stars horizontally as we have only one filled and one empty star. Outer div will show all 5 empty stars and we set its background to stars image. As we set the width of the inner div, filled stars will be placed on top of empty stars but only according to the rating i.e if rating is 4 then 4 filled stars will be placed on top of 5 empty stars giving it the look like we have 4 stars filled out of 5.

This placement of filled stars over empty stars will be done through little CSS.

This is the CSS that we will use. CSS may vary a bit according to outer div:

.ratingbox {
      margin: 0% 25%;
      font-size: 0;
      height: 24px;
      line-height: 0;
      overflow: hidden;
      text-indent: -999em;
      width: 144px;
}

.ratingbox .rating {
      background-position: 0 100% !important;
      float: left;
      height:24px;

}

On applying this , we will have the stars showing rating like in the screenshot below:

Leave a Reply

Your email address will not be published. Required fields are marked *