PHP

Number to Ordinal (1st, 2nd, 3rd)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Convert an integer to its English ordinal form ("1st", "2nd", "3rd", "11th", "22nd", "103rd"). Pure rule-based; no library needed.
PHP
Raw
<?php
function ordinal(int $n): string {
    $abs = abs($n);
    // Special cases for 11/12/13
    if (in_array($abs % 100, [11, 12, 13], true)) return $n . 'th';
    return $n . match ($abs % 10) {
        1 => 'st',
        2 => 'nd',
        3 => 'rd',
        default => 'th',
    };
}

foreach ([1, 2, 3, 4, 11, 12, 21, 22, 101, 103] as $n) {
    echo ordinal($n), ' ';
}
// 1st 2nd 3rd 4th 11th 12th 21st 22nd 101st 103rd
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.