'Star rating with half star support
I am running into a problem rendering a star rating and was hoping I can get some extra eyeballs on my problem. I have the normal rating working just fine with whole numbers but I am struggling to display the half star. For example I created a service that provides me with a rating 0-5 so I get a value like 2.5, 3 or 5 etc...
Before I go and create a switch case and create an svg for each variation I was hoping to get a little a pointer. Below is what I have currently, any tips would be greatly appreciated.
<?php
for ($i = 1; $i <= $totalRating; $i++) {
if($starRating < $i ) {
echo "<img src=\"/icons/star-empty.svg\">";
}
else {
echo "<img src=\"/icons/star.svg\">";
}
}
?>
Ideally I would like to add a condition at the end of the loop and check for the half and echo "";
Solution 1:[1]
There is probably an easier way to do it but this works, checks if $starRating
is a float and then rounds it up and checks against $i
to place the half star in the correct position.
<?php
$totalRating = 5;
$starRating = 2.5;
for ($i = 1; $i <= $totalRating; $i++) {
if($starRating < $i ) {
if(is_float($starRating) && (round($starRating) == $i)){
echo "<img src=\"/icons/star-half.svg\">";
}else{
echo "<img src=\"/icons/star-empty.svg\">";
}
}else {
echo "<img src=\"/icons/star.svg\">";
}
}
?>
Solution 2:[2]
You can verify if the value of $starRating is an integer, doing something like this (considering only half values):
<?php
for ($i = 1; $i <= $totalRating; $i++) {
if ($starRating < $i ) {
echo "<img src=\"/icons/star-empty.svg\">";
} elseif(is_int($starRating) === false) {
echo "<img src=\"/icons/star_half.svg\">";
} else {
echo "<img src=\"/icons/star.svg\">";
}
}
?>
If you want to show stars with a more precise value you can create images with the float values in the name, like "star-3.svg" (representing a .3 float value, and do something like this:
<?php
for ($i = 1; $i <= $totalRating; $i++) {
if ($starRating < $i ) {
echo "<img src=\"/icons/star-empty.svg\">";
} elseif(is_int($starRating) === false) {
echo "<img src=\"/icons/star-" . floatval($starRating)) . ".svg\">";
} else {
echo "<img src=\"/icons/star.svg\">";
}
}
?>
But in this case you need to take care to only receive float values with one number (2.2, 3.4, etc.).
I hope it helps...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Second2None |
Solution 2 | MarcosAM |