Posted By

flashmac on 08/23/10


Tagged

position rank


Versions (?)

Make Position Number


 / Published in: PHP
 

URL: www.stevenmcintosh.co.uk

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

  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

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: feeela on August 24, 2010

Alternative notion, viewer if-statements: function numerals($number) { if(strlen($number) > 1 && 1 == substr($number, -2, -1)) { $lastDigit = 0; } else { $lastDigit = substr($number, -1); }

    switch($lastDigit)
    {
        case 3:
            $numeralAppendix = 'rd';
            break;
        case 2:
            $numeralAppendix = 'nd';
            break;
        case 1:
            $numeralAppendix = 'st';
            break;
        default:
            $numeralAppendix = 'th';
            break;
    }
    return $number . $numeralAppendix;
}

You need to login to post a comment.