Make Position Number


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

If you want to transform an int number to a position number (ie. 1 = 1st, 6 = 6th etc..)


Copy this code and paste it in your HTML
  1. function make_position($position) {
  2. $last = substr( $position, -1 );
  3. $seclast = substr( $position, -2, -1 );
  4. if( $last > 3 || $last == 0 ) $ext = 'th';
  5. else if( $last == 3 ) $ext = 'rd';
  6. else if( $last == 2 ) $ext = 'nd';
  7. else $ext = 'st';
  8.  
  9. if( $last == 1 && $seclast == 1) $ext = 'th';
  10. if( $last == 2 && $seclast == 1) $ext = 'th';
  11. if( $last == 3 && $seclast == 1) $ext = 'th';
  12.  
  13. return $position.$ext;
  14. }
  15.  
  16. eg. make_position(2); // 2nd
  17. eg. make_position(8); // 8th
  18. eg. make_position(21); // 21st
  19. eg. make_position(23); // 23rd

URL: www.stevenmcintosh.co.uk

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.