Skip to content

Instantly share code, notes, and snippets.

@paulferrett
Last active July 2, 2018 21:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulferrett/8103822 to your computer and use it in GitHub Desktop.
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.
<?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>
@uncleramsay
Copy link

uncleramsay commented Jul 2, 2018

I think the << on line 12 is incorrect. It should be < surely?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment