PHP 1st, 2nd, 3rd, 4th, 5th, 6th – PHP Add Ordinal Number Suffix
Table of Contents
This is simple function to add English ordinal number suffix after normal number. Function takes number as a parameter and returns number with suffix, like:
1st, 2nd, 3rd, 4th, 5th, 6th…
This is example table of ordinal numbers 1 to 100⌗
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
11th 12th 13th 14th 15th 16th 17th 18th 19th 20th
21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th
31st 32nd 33rd 34th 35th 36th 37th 38th 39th 40th
41st 42nd 43rd 44th 45th 46th 47th 48th 49th 50th
51st 52nd 53rd 54th 55th 56th 57th 58th 59th 60th
61st 62nd 63rd 64th 65th 66th 67th 68th 69th 70th
71st 72nd 73rd 74th 75th 76th 77th 78th 79th 80th
81st 82nd 83rd 84th 85th 86th 87th 88th 89th 90th
91st 92nd 93rd 94th 95th 96th 97th 98th 99th 100th
Add Ordinal Suffix PHP Function⌗
<?php
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
Add Ordinal Suffix PHP Function Usage/Testing⌗
for ($i = 1; $i <= 10000; $i++){
echo addOrdinalNumberSuffix($i) . "\t";
if ($i % 10 == 0) {
echo "\n";
}
}
Output:
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
11th 12th 13th 14th 15th 16th 17th 18th 19th 20th
21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th
31st 32nd 33rd 34th 35th 36th 37th 38th 39th 40th
41st 42nd 43rd 44th 45th 46th 47th 48th 49th 50th
51st 52nd 53rd 54th 55th 56th 57th 58th 59th 60th
61st 62nd 63rd 64th 65th 66th 67th 68th 69th 70th
71st 72nd 73rd 74th 75th 76th 77th 78th 79th 80th
81st 82nd 83rd 84th 85th 86th 87th 88th 89th 90th
91st 92nd 93rd 94th 95th 96th 97th 98th 99th 100th
101st 102nd 103rd 104th 105th 106th 107th 108th 109th 110th
...
9961st 9962nd 9963rd 9964th 9965th 9966th 9967th 9968th 9969th 9970th
9971st 9972nd 9973rd 9974th 9975th 9976th 9977th 9978th 9979th 9980th
9981st 9982nd 9983rd 9984th 9985th 9986th 9987th 9988th 9989th 9990th
9991st 9992nd 9993rd 9994th 9995th 9996th 9997th 9998th 9999th 10000th