Displaying star rating with Font Awesome icons

  php

Looking to display a score based on a value stored in $averageScore. The value varies from 0 to 5. This is what I currently have, but looks bloated and I am looking for a cleaner solution with PHP:

if( $averageScore = 0 && $averageScore < 0.5 ) {
  $starPattern = array('e', 'e', 'e', 'e', 'e');
} elseif( $averageScore >= 0.5 && $averageScore < 1 ) {
  $starPattern = array('h', 'e', 'e', 'e', 'e');
} elseif( $averageScore >= 1 && $averageScore < 1.5 ) {
  $starPattern = array('f', 'e', 'e', 'e', 'e');
} elseif( $averageScore >= 1.5 && $averageScore < 2 ) {
  $starPattern = array('f', 'h', 'e', 'e', 'e');
} elseif( $averageScore >= 2 && $averageScore < 2.5 ) {
  $starPattern = array('f', 'f', 'e', 'e', 'e');
} elseif( $averageScore >= 2.5 && $averageScore < 3 ) {
  $starPattern = array('f', 'f', 'h', 'e', 'e');
} elseif( $averageScore >= 3 && $averageScore < 3.5 ) {
  $starPattern = array('f', 'f', 'f', 'e', 'e');
} elseif( $averageScore >= 3.5 && $averageScore < 4 ) {
  $starPattern = array('f', 'f', 'f', 'h', 'e');
} elseif( $averageScore >= 4 && $averageScore < 4.5 ) {
  $starPattern = array('f', 'f', 'f', 'f', 'e');
} elseif( $averageScore >= 4.5 && $averageScore < 5) {
  $starPattern = array('f', 'f', 'f', 'f', 'h');
} elseif( $averageScore >= 5  ) {
  $starPattern = array('f', 'f', 'f', 'f', 'f');
}

foreach( $starPattern as $ratingStar ) {
  if( $ratingStar == 'e' ) {
    echo '<i class="far fa-star" text-yellow></i>';
  }
  if( $ratingStar == 'h' ) {
    echo '<i class="fas fa-star-half-alt text-yellow"></i>';
  }
  if( $ratingStar == 'f' ) {
    echo '<i class="fas fa-star text-yellow"></i>';
  }
}

I also have something similar, but it does not cover half stars. I have been trying to combine both, but without success.

$value = $averageScore;
for ($i = 1; $i <= 5; $i++) {
  if ($value >= $i) {
    echo '<i class="fas fa-star"></i>' . PHP_EOL;
  } else {
    echo '<i class="far fa-star"></i>' . PHP_EOL;
  }
}

Any thoughts?

Source: Ask PHP

LEAVE A COMMENT