how to convert number into star rating using php?

Solution 1:

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.

Solution 2:

Here I would like to help other persons who are actually looking for twig template solution....

{% for x in 0..4 %}
   {% if book_data.averageRating|round(2, 'floor') - x >= 1 %}
        <i class="fa fa-star gold"></i>
        {% elseif book_data.averageRating - x > 0 %}
        <i class="fa fa-star-half-o gold"></i>
          {% else %}
        <i class="fa fa-star-o"></i>
   {% endif %}
{% endfor %}