Monday 24 September 2018

Php function to add st, nd, rd, th to the end of numbers

Often numbers are to be written with a proper suffix, like 1st, 2nd, 3rd, 15th, 21st and so on.

So here is a quick function to do the same for a number.
Technique 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
This function will add st, nd, rd, th to the end of numbers
*/
 
function ordinal($i)
{
    $l = substr($i,-1);
    $s = substr($i,-2,-1);
     
    return (($l==1&&$s==1)||($l==2&&$s==1)||($l==3&&$s==1)||$l>3||$l==0?'th':($l==3?'rd':($l==2?'nd':'st')));
}
 
/*
    Example usage
*/
 
for($i = 0; $i < 100; $i++)
{
    echo $i . ordinal($i). '<br />';
}

Technique 2

Php 5.3+ has the NumberFormatter class from the intl pecl package, which can be used to do the same thing in a much better way by taking into account localisation.
To install intl on ubuntu type the following at the terminal
$ sudo apt-get install php5-intl
Example
1
2
$nf = new NumberFormatter('en_US', NumberFormatter::ORDINAL);
print $nf->format(123); // prints 123rd

0 comments:

Post a Comment