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

By | August 4, 2012

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
About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

2 Comments

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

Leave a Reply

Your email address will not be published. Required fields are marked *