number with ordinal suffix [ 1166 views ]
Goal: to show the english ordinal number
I’ve found a very simle solution:
function get_ordinal_suffix($n) {// return English ordinal number
return $n.substr(date('jS', mktime(0,0,0,1,($n%10==0?9:($n%100>20?$n%10:$n%100)),2000)),-2);
};
a simple test and the result
for($i=1; $i<=31;$i++){
echo(ordinal_suffix($i).', ');
}
result:
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
[/php]
or a second solution:
[php]
function ordinalSuffix( $n )
{
return date('S',mktime(1,1,1,1,( (($n>=10)+($n>=20)+($n==0))*10 + $n%10) ));
}
result:
st, nd, rd, th, th, th, th, th, th, th, th, th, th, th, th, th, th, th, th, th, st, nd, rd, th, th, th, th, th, th, th, st


