Create Ordinal Numbers With PHP

11th August 2008 - 2 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'.

  1. function getOrdinal($number){
  2. // get first digit
  3. $digit = abs($number) % 10;
  4. $ext = 'th';
  5. // if the last two digits are between 4 and 21 add a th
  6. if(abs($number) %100 < 21 && abs($number) %100 > 4){
  7. $ext = 'th';
  8. }else{
  9. if($digit < 4){
  10. $ext = 'rd';
  11. }
  12. if($digit < 3){
  13. $ext = 'nd';
  14. }
  15. if($digit < 2){
  16. $ext = 'st';
  17. }
  18. if($digit < 1){
  19. $ext = 'th';
  20. }
  21. }
  22. return $number.$ext;
  23. }

This set of if statements can be shortened by using the ternary control structure.

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

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.

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

 

Comments

Permalink

Just what I was looking for. Thanks!

Joe P (Mon, 04/04/2011 - 19:39)

Add new comment

The content of this field is kept private and will not be shown publicly.