Home > Blockchain >  Showing Star Rating based on text file number in array
Showing Star Rating based on text file number in array

Time:12-29

I have a script which reads an array from a text file and grabs each line and produces star rating images based on number in array. The script is kind of big and was wondering if there was a better way of doing this.

<?php if ($row[2] == '5') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '4.5') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '4') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '3.5') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '3') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '2.5') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '2') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '1.5') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '1') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '.5') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } elseif ($row[2] == '0') { ?>
    <i ></i><i ></i><i ></i><i ></i><i ></i>
<?php } ?>

CodePudding user response:

You can work off this function (doesn't include the half stars, shows you how to do the full star rating - I just noticed you run halfs as well);

function getStars($rating){
    $stars = "";
    $x = 0;
    while($x < $rating) {
      $stars = $stars.'<i ></i>';
      $x  ;
    }
    return $stars;
}

echo getStars(3);

in your case -

echo getStars($row[2]);

You can tweak this that if the number contains a decimal you can append to the string '' for example; you get the gist :P

-------------- Edit

Tweaked it and added the half star rating :)

function getStars($rating){
    $stars = "";
    $x = 1;
    while($x <= $rating) {
      $stars = $stars.'<i ></i>';
      $x  ;
    }
    if (strpos($rating, '.') !== false) {
        $stars = $stars . '<i >';
    }
    return $stars;
}

echo getStars(3.5);

CodePudding user response:

function getStar($rating) {
  $wholeStar = "<i ></i>";
  $halfStar = "<i ></i>";

  // round the rating for whole stars
  $roundedRating = round($rating);

  // Add the whole stars using str_repeat
  $starString = str_repeat($wholeStar, round($rating));

  // Add the half star if the rating is bigger than it's rounded value
  if ($roundedRating < $rating) {
    $starString .= $halfStar;
  }

  return $starString
}

echo getStar($row[2]);

  • Related