Display numbers with ordinal suffix in PHP

ArK picture ArK · Jun 24, 2010 · Viewed 64.9k times · Source

I want to display numbers as follows

  • 1 as 1st,
  • 2 as 2nd,
  • ...,
  • 150 as 150th.

How should I find the correct ordinal suffix (st, nd, rd or th) for each number in my code?

Answer

Iacopo picture Iacopo · Jun 24, 2010

from wikipedia:

$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number %100) >= 11 && ($number%100) <= 13)
   $abbreviation = $number. 'th';
else
   $abbreviation = $number. $ends[$number % 10];

Where $number is the number you want to write. Works with any natural number.

As a function:

function ordinal($number) {
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');
    if ((($number % 100) >= 11) && (($number%100) <= 13))
        return $number. 'th';
    else
        return $number. $ends[$number % 10];
}
//Example Usage
echo ordinal(100);