Add suffix to a number
By: Daniel
Have you ever had to dynamically add the suffix to a number? (ie. st, nd, rd, th)
function number_suffix($i) { switch( floor($i/10) % 10 ) { default: switch( $i % 10 ) { case 1: return 'st'; case 2: return 'nd'; case 3: return 'rd'; } case 1: } return 'th'; }
Then to use the code you would do like:
$number = 10; // This will display 10th echo $number,number_suffix($number);





















July 25th, 2009 at 4:23 am
function suffix($num){
if(strlen($num)>=2 && substr($num, (strlen($num)-2), 1)==1){
$suff = “th”;
} else if(substr($num, (strlen($num)-1), 1)==1){
$suff = “st”;
} else if(substr($num, (strlen($num)-1), 1)==2){
$suff = “nd”;
} else if(substr($num, (strlen($num)-1), 1)==3){
$suff = “rd”;
} else if(substr($num, (strlen($num)-1), 1)>>2 && substr($num, (strlen($num)-1), 1)<=9 || substr($num, (strlen($num)-1), 1)==0){
$suff = "th";
}
$suffixedNum = $num.$suff;
return $suffixedNum;
}
Someone posted that way iam wondering if it even has the same result
July 31st, 2009 at 2:27 pm
Yes, it does have the same result but uses more code than the article above.
I did a test and used microtime() to calculate the start time, then looped through 1000 numbers echoing out the result for the commenter above and then used microtime() again to calculate how long it took to loop through the code. On my machine it took 0.008 seconds to echo 1000 numbers.
Doing the same with the function in the article above I came up with around: 0.002 seconds.