Cardinal Endings for Numbers

Released on December 2, 2002
Last Updated: December 2, 2002 9:46 PM
Version: 1


Adds cardinal endings to numbers, like 1st and 2nd, and doesn’t do much else. Has an option or two that might make this useful for you.


This adds proper ending for numbers, ie 2nd, 3rd, 8th, with optionally outputting the ending as superscript. Just drop it in your script and have fun. I use it for formatting ages on but you could really use it for any number. An oldie but a goodie.


nthnum function

function nthnum ($age,$small=0) { // proper ending for numbers, ie 2nd, 3rd, 8th
    $last_char_age = substr("$age", -1);
    switch($last_char_age) {
        case '1' :
            $th = 'st';
        case '2' :
            $th = 'nd';
        case '3' :
            $th = 'rd';
        default :
            $th = 'th';
    if ($age > 10 && $age < 20) $th = 'th';
    if (0 == $small) $niceage = $age.$th;
    if (1 == $small) $niceage = $age."<sup>$th</sup>";
    return $niceage;

2 thoughts on “Cardinal Endings for Numbers

  1. A couple things:

    In the third line you should probably use modulus and subsequently compare it to integers rather than strings. That is, set the 3rd line to: $last_char_age = $age % 10;
    For each of the “cases”, remove the single quotes from the numbers.

    Numbers >100 that end in 10..19 should *always* have th. A fix to this: instead of the line starting with “if ($age >” etc, use this:
    if (($age % 100) > 10 && ($age % 100) < 20)

    You should also replace “if (0 == $small)” by “if (!$small)” and “if (1 == $small)” by “else” – it is a boolean parameter – not technically, but pragmatically. Surely a number can still be passed, but in its meaning it is a boolean parameter.