I'm displaying star ratings based on input from an API (note: only displaying, not receiving ratings at all). The following code works exactly as I need it to, but it's a very large piece of logic for something that feels like it could be massively simplified.
I read a few other tickets here that suggest that using an array might be more effective than a switch case. But because the logic depends on each case between true within a range of numbers (like more than 2.5 but less than 3) I'm not sure an array would work at all in this case.
Bottom line is this: Can this code be massively simplified somehow?
$stars = 3.5;
switch ($stars) {
case ($stars > 1 && $stars <= 1.5):
$star2 = 'dashicons-star-half';
$star3 = 'dashicons-star-empty';
$star4 = 'dashicons-star-empty';
$star5 = 'dashicons-star-empty';
break;
case($stars > 1.5 && $stars <= 2):
$star2 = 'dashicons-star-filled';
$star3 = 'dashicons-star-empty';
$star4 = 'dashicons-star-empty';
$star5 = 'dashicons-star-empty';
break;
case($stars > 2 && $stars <= 2.5):
$star2 = 'dashicons-star-filled';
$star3 = 'dashicons-star-half';
$star4 = 'dashicons-star-empty';
$star5 = 'dashicons-star-empty';
break;
case($stars > 2.5 && $stars <= 3):
$star2 = 'dashicons-star-filled';
$star3 = 'dashicons-star-filled';
$star4 = 'dashicons-star-empty';
$star5 = 'dashicons-star-empty';
break;
case($stars > 3 && $stars <= 3.5):
$star2 = 'dashicons-star-filled';
$star3 = 'dashicons-star-filled';
$star4 = 'dashicons-star-half';
$star5 = 'dashicons-star-empty';
break;
case($stars > 3.5 && $stars <= 4):
$star2 = 'dashicons-star-filled';
$star3 = 'dashicons-star-filled';
$star4 = 'dashicons-star-filled';
$star5 = 'dashicons-star-empty';
break;
case($stars > 4 && $stars <= 4.5):
$star2 = 'dashicons-star-filled';
$star3 = 'dashicons-star-filled';
$star4 = 'dashicons-star-filled';
$star5 = 'dashicons-star-half';
break;
case($stars > 4.5):
$star2 = 'dashicons-star-filled';
$star3 = 'dashicons-star-filled';
$star4 = 'dashicons-star-filled';
$star5 = 'dashicons-star-filled';
break;
default:
$star2 = 'dashicons-star-empty';
$star3 = 'dashicons-star-empty';
$star4 = 'dashicons-star-empty';
$star5 = 'dashicons-star-empty';
}
?>
<div class="wporg-ratings" title="<?php echo $stars; ?> out of 5 stars" style="color:#e6b800;">
<span class="dashicons dashicons-star-filled"></span>
<span class="dashicons <?php echo $star2; ?>"></span>
<span class="dashicons <?php echo $star3; ?>"></span>
<span class="dashicons <?php echo $star4; ?>"></span>
<span class="dashicons <?php echo $star5; ?>"></span>
</div>