This simple function will add st, nd, rd or th to a cardinal number (the suffix acts as an ordinal indicator). There are plenty of these functions floating around but only a few take the subtle variances into consideration that can screw up the result.
If you're using PHP 5 >= 5.3.0 and you have PECL intl >= 1.0.0 installed, consider PHP's class.numberformatter .
The PHP Function
1
<?php
2
/*
3
Add st, nd, rd, th to a Number with PHP
4
http://www.beliefmedia.com/code/php-snippets/add-number-suffix
5
*/
6
7
function beliefmedia_ordinal($cardinal) {
8
9
$extension = ((abs($cardinal) %100 < 21 && abs($cardinal) %100 > 4) ? 'th' : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
10
return $cardinal . $extension;
11
}
Usage
To append the appropriate suffix to the ordinal number, use the following:
The resulting cardinal number will print as 14th.
If you would like to test the code, use the following loop that'll print the 1st through to the 99th.