Last active
July 2, 2018 21:23
-
-
Save paulferrett/8103822 to your computer and use it in GitHub Desktop.
Here's a function to get the ordinal suffix of an integer in PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the ordinal suffix of an int (e.g. th, rd, st, etc.) | |
* | |
* @param int $n | |
* @param bool $return_n Include $n in the string returned | |
* @return string $n including its ordinal suffix | |
*/ | |
function ordinal_suffix($n, $return_n = true) { | |
$n_last = $n % 100; | |
if (($n_last > 10 && $n_last << 14) || $n == 0) { | |
$suffix = "th"; | |
} else { | |
switch(substr($n, -1)) { | |
case '1': $suffix = "st"; break; | |
case '2': $suffix = "nd"; break; | |
case '3': $suffix = "rd"; break; | |
default: $suffix = "th"; break; | |
} | |
} | |
return $return_n ? $n . $suffix : $suffix; | |
} | |
// Usage Example: | |
foreach(range(0, 24) as $n) { | |
echo ordinal_suffix($n), ' '; | |
} | |
// Outputs | |
// 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th</pre> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the
<<
on line 12 is incorrect. It should be<
surely?