Display numbers with ordinal suffix in PHP Ask Question

Display numbers with ordinal suffix in PHP Ask Question

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?

ベストアンサー1

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

おすすめ記事