Lecture
How do you add the suffix st, nd, rd or th to ordinal numbers in English in PHP?
For this you can use a custom function or a built-in one
function ordinalSuffix($number) {
if ($number % 100 >= 11 && $number % 100 <= 13) {
return $number . 'th';
} else {
switch ($number % 10) {
case 1: return $number . 'st';
case 2: return $number . 'nd';
case 3: return $number . 'rd';
default: return $number . 'th';
}
}
}
// Example usage:
echo ordinalSuffix(1); // Output: 1st
echo ordinalSuffix(22); // Output: 22nd
echo ordinalSuffix(103); // Output: 103rd
echo ordinalSuffix(4); // Output: 4th
echo ordinalSuffix(11); // Output: 11th
echo ordinalSuffix(112); // Output: 112th
// and so on...
PHP has built-in functionality for this. It even handles internationalization!
$locale = 'en_US';
$nf = new NumberFormatter($locale, NumberFormatter::ORDINAL);
echo $nf->format($number);
Note that this function is only available in PHP 5.3.0 and later versions
Numerals come in two kinds: cardinal and ordinal. The first denote quantity, the second denote a number in a sequence.
Note: ordinal numerals do not vary by gender or number:
Fourth book – четвёртая книга
Fourth armchair – четвёртое кресло
Fourth guest – четвёртый гость
Fourth trousers – четвёртые брюки
The first three have a special form:
First – first (1st)
Second – second (2nd)
Third – third (3rd)
After that, the suffix -th is added to the form of the cardinal numeral, and for some the spelling also changes slightly:
Fourth – fourth (4th)
Fifth – fifth (5th)
Sixth – sixth (6th)
Seventh – seventh (7th)
Eighth – eighth (8th)
Ninth – ninth (9th)
Tenth – tenth (10th)
Eleventh – eleventh (11th)
Twelfth – twelfth (12th)
Thirteenth – thirteenth (13th)
Fourteenth – fourteenth (14th)
Fifteenth – fifteenth (15th)
Sixteenth – sixteenth (16th)
Seventeenth – seventeenth (17th)
Eighteenth – eighteenth (18th)
Nineteenth – nineteenth (19th)
For all numerals denoting tens, the letter -y- changes to -ie-:
Twentieth – twentieth (20th)
Thirtieth – thirtieth (30th)
Fortieth – fortieth (40th)
Fiftieth – fiftieth (50th)
Sixtieth – sixtieth (60th)
Seventieth – seventieth (70th)
Eightieth – eightieth (80th)
Ninetieth – ninetieth (90th)
If you need to form a compound numeral, only the last digit takes the ordinal form:
Twenty-first – twenty-first (21st)
Forty-seventh – forty-seventh (47th)
Formation of hundreds:
Hundredth – hundredth (100th)
Two hundredth – two hundredth (200th)
Two hundred and first – two hundred and first (201st)
Seven hundred and fiftieth – seven hundred and fiftieth (750th)
Also, the conjunction and must be used between hundreds and units.
Similar rules are used for writing other numbers:
Thousandth – thousandth (1,000th)
Millionth – millionth (1,000,000th)
The definite article the is placed before ordinal numerals:
the first day – the first day
the fifth chapter – the fifth chapter
Comments