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.
Just use like this:
$n = is_int($av) ? $av : floor($av) + 0.5;
echo '/images/'.$n.'-star.png';
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...
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With