PHP Ordinal Numbers. 3rd, 4th, 1st, etc.


Here is a little function you can use to get the proper ordinal. Works for negative numbers too:

     function ordinal($number) {

    // when fed a number, adds the English ordinal suffix. Works for any
    // number, even negatives

    if ($number % 100 > 10 && $number %100 < 14):
        $suffix = "th";
    else:
        switch($number % 10) {

            case 0:
                $suffix = "th";
                break;

            case 1:
                $suffix = "st";
                break;

            case 2:
                $suffix = "nd";
                break;

            case 3:
                $suffix = "rd";
                break;

            default:
                $suffix = "th";
                break;
        }

    endif;

    return "${number}$suffix";

}

Usage:
Just call it with ordinal(179) and you will get back, 179th
Cool eh?

  1. No comments yet.
(will not be published)
Security Code:

  1. No trackbacks yet.