# 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&amp;&amp;\$s==1)||(\$l==2&amp;&amp;\$s==1)||(\$l==3&amp;&amp;\$s==1)||\$l&gt;3||\$l==0?'th':(\$l==3?'rd':(\$l==2?'nd':'st')));
}

/*
Example usage
*/

for(\$i = 0; \$i &lt; 100; \$i++)
{
echo \$i . ordinal(\$i). '&lt;br /&gt;';
}```

### 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-&gt;format(123); // prints 123rd```
Last Updated On : 4th August 2012
```

```

## 2 thoughts on “Php function to add st, nd, rd, th to the end of numbers”

1. Spudley

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

1. Silver Moon Post author

thanks, thats very useful. added it to the post.