Jump to content

Star rating with halves


-Karl-

Recommended Posts

What's the best way to display a star rating, which includes half values.

 

At the moment I have:

$value = 3.66;
$value = round(($value*2), 0)/2;

switch($value) {
    case 0:
        echo 0 stars;
    break;
    case 0.5:
        echo half a star;
    break;
}

 

What's a more efficient way to do this?

Link to comment
https://forums.phpfreaks.com/topic/264837-star-rating-with-halves/
Share on other sites

Probably lots of ways to accomplish it, but this was the first one that popped in my mind:

 

$stars = 3.66;
$full = floor($stars);
$half = round( (($stars * 100) % 100) / 100);
echo "$full stars, $half half stars";

Well, I could see where one would expect 3.9 to produce 4 full stars. Otherwise, it would be impossible for an item to have 5 full starts (assuming 5 is the max) if there is even one rating less than 5. I would round the value to the nearest 1/2 value.

 

Then assuming the "stars" are images you need to output the full, half and stars. You could use multiple images with all five stars together and simply name them using the numeric value: star_0, start_0.5, star_1.0, etc. Or you can do the logic in a loop, i.e. for $i=0 to 5 and do a comparison on each iteration. But, I think single images for all five stars is the easiest.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.