Star Rating

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kkonline
Forum Contributor
Posts: 251
Joined: Thu Aug 16, 2007 12:54 am

Star Rating

Post by kkonline »

I am using

echo $row['votes']+1;
for ($i = 0; $i < (int)$row["rating"]; $i++) {
echo '<img src="rate1.gif">';
}

to show the stars according to the rating.
If i have rating >4.5 then it comes to 4 after type casting and show 4 stars. However i want to show another half star image for anything > 4.49 and below 5 ... or 3.49 and below 4.

That means if the rating is 4.57 then it should show 4 rate1.gif image and then one half star image. How to do this?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

I did something like this.

Code: Select all

if(!isset($imga['rating']) || ($imga['rating'] == ''))
{
	$rating = 'rating_notrated.gif';
	$ratingalt = 'This image has not yet been rated.';
} else
{
	if($rating = explode('.', $imga['rating']))
	{
		$ratings = (int) $rating[0];
		$ratings_part = $rating[1];
		
		if(strlen($ratings_part) > 2)
		{
			$ratings_part = substr($ratings_part, 0, 2);
		} elseif(strlen($ratings_part) == 1)
		{
			$ratings_part = $ratings_part.'0';
		} elseif(strlen($ratings_part) == 0)
		{
			$ratings_part = '00';
		}
	} else
	{
		$ratings = (int) $imga['rating'];
		$ratings_part = '00';
	}
	
	if($ratings_part < 25)
	{
		$ratings_part = '.gif';
	} elseif($ratings_part < 50)
	{
		$ratings_part = '.5.gif';
	} elseif($ratings_part < 75)
	{
		$ratings_part = '.5.gif';
	} elseif($ratings_part < 100)
	{
		$ratings = $ratings+1;
		$ratings_part = '.gif';
	}
	
	$rating = 'rating_' . $ratings . $ratings_part;
	$ratingalt = 'This image is rated a ' . $ratings . str_replace('.gif', '', $ratings_part) . ' out of 5';
}
This would give me a 0.5.gif, 1.0.gif, 1.5.gif, 2.0.gif, 2.5.gif etc up to 5. It could easily be manipulated to fit your scenario, though.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

Code: Select all

$k = round($rating * 2) / 2;
$n = (int) $k;

echo str_repeat("<img star>", $n);
if($n != $k)
	echo "<img half-star>";
Post Reply