Tag: ordinalize

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:

[code lang=”php”]
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;
}
}
}
[/code]

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:

[code]
3
10
999
[/code]

Example output:

[code]
3rd
10th
999th
[/code]

Enjoy!

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , ,