Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best star rating solution for PHP

Tags:

php

I'm wondering what the best and most efficient way to write up the following PHP code would be?

    if ($av == 1) echo '/images/1-star.png';
    if ($av > 1 && < 2) echo '/images/1-half-star.png';
    if ($av == 2) echo '/images/2-star.png';
    if ($av > 2 && < 3) echo '/images/2-half-star.png';

Following this same pattern up to 5 stars.

like image 507
user537137 Avatar asked Sep 06 '25 17:09

user537137


2 Answers

Just use like this:

$n = is_int($av) ? $av : floor($av) + 0.5;
echo '/images/'.$n.'-star.png';

enter image description here

Cut images per line and name it "1-star.png", "1.5-star.png", "2-star.png", "2.5-star.png", "3-start.png", "3.5-star.png" and so on...

like image 67
Community Driven Business Avatar answered Sep 09 '25 12:09

Community Driven Business


This may not be the most efficient way. But I find it clean code. Check this.

function renderStarRating($rating,$maxRating=5) {
    $fullStar = "<li><i class = 'fa fa-star'></i></li>";
    $halfStar = "<li><i class = 'fa fa-star-half-full'></i></li>";
    $emptyStar = "<li><i class = 'fa fa-star-o'></i></li>";
    $rating = $rating <= $maxRating?$rating:$maxRating;

    $fullStarCount = (int)$rating;
    $halfStarCount = ceil($rating)-$fullStarCount;
    $emptyStarCount = $maxRating -$fullStarCount-$halfStarCount;

    $html = str_repeat($fullStar,$fullStarCount);
    $html .= str_repeat($halfStar,$halfStarCount);
    $html .= str_repeat($emptyStar,$emptyStarCount);
    $html = '<ul>'.$html.'</ul>';
    return $html;
}
like image 22
Jinu Joseph Daniel Avatar answered Sep 09 '25 13:09

Jinu Joseph Daniel