14

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
422
  • 5,714
  • 23
  • 83
  • 139

1 Answers1

37

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...)

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160