Number suffix

Adds a suffix to a given number (1st, 2nd, 3rd, ...)

// Also, increasing the range above the condition statements
// increases efficiency. That's almost 20% of the numbers 
// between 0 and 100 that get to end early.
 
function number_suffix($number){
 
    // Validate and translate our input
    if ( is_numeric($number)){
 
        // Get the last two digits (only once)
        $n = $number % 100;
 
    } 
    else {
        // If the last two characters are numbers
        if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches )){
 
            // Return the last one or two digits
            $n = array_pop($matches);
        } 
        else {
 
            // Return the string, we can add a suffix to it
            return $number;
        }
    }
 
    // Skip the switch for as many numbers as possible.
    if ( $n > 3 && $n < 21 )
        return $number . 'th';
 
    // Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
    switch ( $n % 10 ){
        case '1': return $number . 'st';
        case '2': return $number . 'nd';
        case '3': return $number . 'rd';
        default:  return $number . 'th';
    }
}
Snippet Details



print number_suffix(3);
//returns: 3rd
 
print number_suffix(51);
//returns: 51st
 
print number_suffix(94859);
//returns: 94859th

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Ian February 18, 2011 at 14:38
11 returns 11st not 11th
12 returns 12nd not 12th
13 returns 13rd not 13th

111 returns 111st not 111th
... etc
df August 21, 2010 at 11:02
fdafaf
Paul Baker January 07, 2010 at 18:53
Vez, thanks, didn't work for me but this modified version appears to be OK:

function number_suffix ($n) {
$suffix = 'th';
if(!($n >= 10 && $n < 20)) {
$s = array ('st','nd','rd');
$s = $s[$n % 10 - 1];
$suffix = $s ? $s : 'th';
}
return $n . $suffix;
}
Vez July 28, 2008 at 14:59
My bad. Ignore one of the opening braces.
Vez July 28, 2008 at 14:55
function number_suffix($n){
{
$suffix = 'th';
if(!($n >= 10 && $n < 20));
{
$s = ['st','nd','rd'];
$s = $s[$n % 10 - 1];
$suffix = $s ? $s : 'th';
}
return $n . $suffix;
}