stavros-s
8/14/2013 - 7:22 PM

PHP Snippet: Add (th, st, nd, rd, th) to the end of a number: This PHP code snippet will add the appropriate suffix th, st, nd and rd to

PHP Snippet: Add (th, st, nd, rd, th) to the end of a number:

This PHP code snippet will add the appropriate suffix th, st, nd and rd to a given number.

<?php


  function ordinal($num)
  {

    $last=substr($num,-1);


    if( $last>3  or 
        $last==0 or 
        ( $num >= 11 and $num <= 19 ) )
    {

      $ext='th';

    }
    else if( $last==3 )
    {

      $ext='rd';

    }
    else if( $last==2 )
    {

      $ext='nd';

    }
    else 
    {

      $ext='st';

    }


    return $num.$ext;

  }



  print "<p>1 becomes ".ordinal(1)."</p>";

  print "<p>5 becomes ".ordinal(5)."</p>";

  print "<p>10 becomes ".ordinal(10)."</p>";

  print "<p>12 becomes ".ordinal(11)."</p>";

  print "<p>20 becomes ".ordinal(20)."</p>";

  print "<p>22 becomes ".ordinal(22)."</p>";

  print "<p>33 becomes ".ordinal(33)."</p>";


?>