0

I have a numeric value from an array

<p><b>Rating</b>: <?= $arr->rating; ?></p>

which outputs in browser source code

<p><b>Rating</b>: 5.100000</p>

(This is a rating of 5.100000 out of 10.)

How would I go about displaying the rating numeric value as an array of five stars?

For example, the 5.100000 values would be displayed as two and 1/2 stars out of five like this.

<li>
    <i class="glyphicon glyphicon-star"></i>
    <i class="glyphicon glyphicon-star"></i>
    <i class="glyphicon glyphicon-star half"></i>
    <i class="glyphicon glyphicon-star empty"></i>
    <i class="glyphicon glyphicon-star empty"></i>
</li>
9
  • 4
    html... array...? That's not a thing. Your question is very hard to understand. Commented Aug 10, 2017 at 16:30
  • can you give us an example of what you need as final result? Commented Aug 10, 2017 at 16:33
  • 2
    I think what you're trying to say is that you want to automatically generate the required number of stars (and half stars) based on a number. Commented Aug 10, 2017 at 16:35
  • 3
    how can 5.1 result in 2.5 stars? Commented Aug 10, 2017 at 16:39
  • 1
    "how can 5.1 result in 2.5 stars" 5.1 out of 10 rounds to 5. the conversion is 1/2-5 stars out of a 1-10 rating. Commented Aug 10, 2017 at 16:44

1 Answer 1

2

Use a for loop and compare the current loop iteration to $arr->rating to determine whether the star should be full, half, or empty.

// first convert the rating from score out of ten to score out of five
$rating = $arr->rating / 2;  

for ($i=0; $i < 5; $i++) {
    $current = $rating - $i;
    if ($current >= 1) {
        $class = '';
    } elseif ($current > 0) {
        $class = 'half';
    } else {
        $class = 'empty';
    }
    echo "<i class=\"glyphicon glyphicon-star $class\"></i>";
} ?>
Sign up to request clarification or add additional context in comments.

1 Comment

I think $current = $arr->rating - $i; should be $current = $rating - $i;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.