Parker February 2016

how to convert number into star rating using php?

I have a page where i need to show star rating system. converting number to visually star image. i have 1.5,2,2.5,..5.0. I have a code shows converting number but 5.0 showing 6 star

followed this code

Converting numbers to visual rating (stars)?

  $starNumber = 5.0;

  for ($x = 1; $x <= $starNumber; $x++) {
      echo '<li><i class="fa fa-star"></i></li>';
  }
  if (strpos($starNumber, '.')) {
      echo '<li><i class="fa fa-star-half-o"></i></li>';
      $x++;
  }
  while ($x <= 5) {
      echo '<li><i class="fa fa-star-o"></i></li>';
      $x++;
  }

Showing as 6 stars

Answers


ameenulla0007 February 2016

$starLimit  = 5;
$liStarRate = "";
for($star=1; $star<=$starLimit; $star++) {
    //this holds .5 values
    $liStarRate.='<li star-rate="'.($star-.5).'"><i class="fa fa-star-half-o"></i></li>';
    //this holds the whole values
    $liStarRate.='<li star-rate="$star"><i class="fa fa-star-o"></i></li>';
}

use a simple looping statement as above, where you don't require any conditional statements, as every whole number can be changed to float by simply subtracting 0.5 on it.


fusion3k February 2016

My solution:

for( $x = 0; $x < 5; $x++ )
{
    if( floor( $starNumber )-$x >= 1 )
    { echo '<li><i class="fa fa-star"></i></li>'; }
    elseif( $starNumber-$x > 0 )
    { echo '<li><i class="fa fa-star-half-o"></i></li>'; }
    else
    { echo '<li><i class="fa fa-star-o"></i></li>'; }
}

PhpFiddle demo

With only one foor loop I compare floor value (float rounded down) of $starNumber to curren $x value to echo full-star; otherwise if not rounded value is greater than current $x I echo half-star; otherwise (value lower than current $x) I echo empty-star.

Post Status

Asked in February 2016
Viewed 1,295 times
Voted 11
Answered 2 times

Search




Leave an answer