PHP Star Rating function


/ Published in: PHP
Save to your folder(s)

I recently wanted to use stars to show my skill levels in various aspects of web design in my portfolio e.g, PHP, MySQL etc; similar to a rating system. It would be repetitive to have to copy the HTML image code over and over or to design various ratings in photoshop.

So I came up with this function, all you need are three images: a full rating star, a half rating star and an grayed out unrated star


Copy this code and paste it in your HTML
  1. function display_skill_level ( $number ) {
  2. // Convert any entered number into a float
  3. // Because the rating can be a decimal e.g. 4.5
  4. $number = number_format ( $number, 1 );
  5.  
  6. // Get the integer part of the number
  7. $intpart = floor ( $number );
  8.  
  9. // Get the fraction part
  10. $fraction = $number - $intpart;
  11.  
  12. // Rating is out of 5
  13. // Get how many stars should be left blank
  14. $unrated = 5 - ceil ( $number );
  15.  
  16. // Populate the full-rated stars
  17. if ( $intpart <= 5 ) {
  18. for ( $i=0; $i<$intpart; $i++ )
  19. echo '<img src="/images/star-rating-full.png" />';
  20. }
  21.  
  22. // Populate the half-rated star, if any
  23. if ( $fraction == 0.5 ) {
  24. echo '<img src="/images/star-rating-half.png" />';
  25. }
  26.  
  27. // Populate the unrated stars, if any
  28. if ( $unrated > 0 ) {
  29. for ( $j=0; $j<$unrated; $j++ )
  30. echo '<img src="/images/star-rating-none.png" />';
  31. }
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.