Create Ordinal Numbers With PHP

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.

function getOrdinal($number){
 // get first digit
 $digit = abs($number) % 10;
 $ext = 'th';
$ext = ((abs($number) %100 < 21 && abs($number) %100 > 4) ? 'th' : (($digit < 4) ? ($digit < 3) ? ($digit < 2) ? ($digit < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
 return $number.$ext;
}

This is a little be harder to read, but it takes up less space and there is little need to change it unless you want to change the language.

Here is an example of the code in action.

echo getOrdinal(1); //1st
echo getOrdinal(2); //2nd
echo getOrdinal(3); //3rd
echo getOrdinal(4); //4th
echo getOrdinal(11); //11th
echo getOrdinal(87654311); //87654311th

 

Comments

Just what I was looking for. Thanks!

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.