Convert a number to a position / ranking


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

Convert an number to a position / ranking. 1 becomes 1st, 2 becomes 2nd, etc...


Copy this code and paste it in your HTML
  1. function numberToPlace($number) {
  2.  
  3. if(!is_numeric($number)) return false;
  4. $number = intval($number);
  5. $lastNumber = substr($number, -1);
  6. $lastTwo = substr($number, -2);
  7.  
  8. $append = ($lastNumber == '1' && $lastTwo != 11) ? 'st' : (($lastNumber == '2' && $lastTwo != 12) ? 'nd' : (($lastNumber == '3' && $lastTwo != 13) ? 'rd' : 'th'));
  9.  
  10. return $number . $append;
  11. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.