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
/* 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
$nf = new NumberFormatter('en_US', NumberFormatter::ORDINAL); print $nf->format(123); // prints 123rd
Simple enough code, but it takes no account of localisations.
PHP 5.3 has this available in the NumberFormatter class in the localisation extension:
$nf = new NumberFormatter(‘en_US’, NumberFormatter::ORDINAL);
print $nf->format(123); // prints 123rd
See http://stackoverflow.com/questions/2453594/localize-ordinal-numbers
thanks, thats very useful. added it to the post.