Add suffix to a number

Have you ever had to dynamically add the suffix to a number? (ie. st, nd, rd, th)

<?php
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:

<?php
$number = 10;
// This will display 10th
echo $number,number_suffix($number);
?>
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • BlinkList
  • FriendFeed
  • LinkedIn
  • MySpace
  • Slashdot
  • StumbleUpon
  • Twitter
  • Yahoo! Bookmarks
  • Add to favorites
  • email

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>