<?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
Create a free account and build your private vault. Share publicly whenever you want.