Home Add st, nd, rd, th to a Number with PHP

    Add st, nd, rd, th to a Number with PHP


    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


    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.

    Shortt URL for this post: http://shor.tt/2nTC