Ordinal Suffix
This function will append the ordinal suffix to a number. If you need this for dates, the PHP date() function has an option for this. For all other times you need to supply add st, nd, rd, th.
An additional parameter has been added so the ordinal suffix can be in superscript.
<?php
/**
*
* @return number with ordinal suffix
*
* @param int $number
*
* @param int $ss Turn super script on/off
*
* @return string
*
*/
function ordinalSuffix($number, $ss=0)
{
/*** check for 11, 12, 13 ***/
if ($number % 100 > 10 && $number %100 < 14)
{
$os = 'th';
}
/*** check if number is zero ***/
elseif($number == 0)
{
$os = '';
}
else
{
/*** get the last digit ***/
$last = substr($number, -1, 1);
switch($last)
{
case "1":
$os = 'st';
break;
case "2":
$os = 'nd';
break;
case "3":
$os = 'rd';
break;
default:
$os = 'th';
}
}
/*** add super script ***/
$os = $ss==0 ? $os : '<sup>'.$os.'</sup>';
/*** return ***/
return $number.$os;
}
?>
Example Usage
<?php
/*** without super script ***/
echo ordinalSuffix(222);
/*** with super script ***/
echo ordinalSuffix(21, 1);
?>