This function will allow you to add an ordinal suffix or indicator to the number you pass in. Typically this would be for an ordinal number which is a number that usually represent position or rank. For example 1st place, 2nd place, and 3rd place. Or after my 17th attempt, this function is now complete.
Optionally you can pass in a 2nd parameter like 'sup' which will wrap the ordinal indicator with a HTML tag <sup>
. The end result for ordinal(3, 'sup')
would be 3<sup>rd</sup>
.
/**
* Display ordinal numbers with suffix, or otherwise known as ordinal indicator
*
* @param int $number Any ordinal number that needs an ordinal suffix added
* @param null $markup Surround ordinal indicator with markup, often used with: 'sup'
* @return string Returns the number with the ordinal indicator added
*/
function ordinal($number, $markup = null): string
{
$indicator = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
if ($markup) {
$indicator = array_map(function ($end) use ($markup) {
return "<$markup>" . $end . "</$markup>";
}, $indicator);
}
if ((($number % 100) >= 11) && (($number % 100) <= 13)) {
return $number . $indicator[0];
}
return $number . $indicator[$number % 10];
}
This code snippet was published on It was last edited on