Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add 'rd or 'th or 'st dependent on number [duplicate]

Tags:

php

Possible Duplicate:
Display numbers with ordinal suffix in PHP

I think they are called Ordinal suffixes.

Have seen examples for dates...

But just wondered if there was some php that can spew out the suffix dependant on number.

Example: we are spewing out the leaderboard score of our users.

So member ranked number 1. we wish to echo: 1'st and member ranked 847. we want to spew out 847'th

etc etc

I cannot give example, as the numbers are rendered on page via our dB

Just wondered if there was some sort of code snippet, that could add automagically 'th or 'st or 'rd to the appropriate number.

like image 992
422 Avatar asked Jul 07 '11 01:07

422


1 Answers

I don't know of any built-ins that do this, but this should work:

function ordinal_suffix($num){
    $num = $num % 100; // protect against large numbers
    if($num < 11 || $num > 13){
         switch($num % 10){
            case 1: return 'st';
            case 2: return 'nd';
            case 3: return 'rd';
        }
    }
    return 'th';
}

(note 11, 12 and 13 are special cases - 11th, 12th, 13th vs 11st...)

like image 63
Mark Elliot Avatar answered Nov 07 '22 06:11

Mark Elliot