Tuesday, April 11, 2017

Display numbers with ordinal suffix/position in PHP

I want to display numbers/any position like merit position as follows
  • 1 as 1st,
  • 2 as 2nd,
  • 3 as 3rd
  • 21 as 21st
  • ...,
  • 150 as 150th.
As a function:
function ordinal_position($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_position(121);
// show 121st


No comments:

Post a Comment

Total Pageviews