PHP Ordinalize Numbers – Add Suffix

Here is a very simple function to use to ordinalize numbers in PHP. This adds the place value suffix to numbers. So you can turn numbers like 1, 2, 3 into 1st, 2nd, 3rd.

Here is the code:

function ordinalize($int){
if(in_array(($int % 100),range(11,13))){
return $int . "th";
} else {
switch(($int % 10)){
case 1:
return $int . "st";
break;
case 2:
return $int . "nd";
break;
case 3:
return $int . "rd";
break;
default:
return $int . "th";
break;
}
}
}

Basically the function first checks if the number is in the range of 11-13, and if so it returns the number with “th” attached (11th, 12th, 13th). If it is not in this range it checks the remainder of the number divided by 10.

So let’s say our number was 34. 10 goes into 34 three times, with a remainder of 4. Now the function runs this value against three cases, those being 1, 2, and 3. Since it is not one of them, the default value is used, which is “th.” Thus returning “4th.”

Example input:

3
10
999

Example output:

3rd
10th
999th

Enjoy!

1

Popularity: 2% [?]

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Filed Under: PHPTutorialsWeb Programming

Tags:

RSSComments (2)

Leave a Reply | Trackback URL

  1. Hassan Guard says:

    This is a useful post about style. I’m a student just trying to learn more about trends and I really enjoyed your post. Keep up the great work!

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.

The tutorials and scripts found on bgallz.org are for training purposes only, use to your discretion.