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 class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i>
<?php } elseif ($row[2] == '4.5') { ?>
<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half-o"></i>
<?php } elseif ($row[2] == '4') { ?>
<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '3.5') { ?>
<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half-o"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '3') { ?>
<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '2.5') { ?>
<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '2') { ?>
<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '1.5') { ?>
<i class="fa fa-star"></i><i class="fa fa-star-half-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '1') { ?>
<i class="fa fa-star"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '.5') { ?>
<i class="fa fa-star-half-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i>
<?php } elseif ($row[2] == '0') { ?>
<i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i><i class="fa fa-star-o"></i>
<?php } ?>
3
Answers
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);
in your case –
You can tweak this that if the number contains a decimal you can append to the string ” for example; you get the gist 😛
————– Edit
Tweaked it and added the half star rating 🙂
Yes, better ways… A loop will help, maybe something like this (PHP demo at tio.run).