11th August 2008 - 3 minutes read time
An ordinal number is just a way of saying that position the number is in. So for the number 1 the ordinal version of this is 1st. 2 is 2nd, 3 is 3rd and so on.
The following function will work out what ordinal text should be placed behind a number. This will be one of 'st', 'nd', 'rd' and 'th'.
function getOrdinal($number){
// get first digit
$digit = abs($number) % 10;
$ext = 'th';
// if the last two digits are between 4 and 21 add a th
if(abs($number) %100 < 21 && abs($number) %100 > 4){
$ext = 'th';
}else{
if($digit < 4){
$ext = 'rd';
}
if($digit < 3){
$ext = 'nd';
}
if($digit < 2){
$ext = 'st';
}
if($digit < 1){
$ext = 'th';
}
}
return $number.$ext;
}
This set of if statements can be shortened by using the ternary control structure.