Wednesday, May 13, 2015

Ordinal Number

Here is a PHP function to get the ordinal number. Pass it a number, and it will return a textual number suffixed with either of "st" (like 1st), "nd" (like 2nd), "rd" (like 3rd), "th" (like 4th) etc.

<?php
/**
* ordinal_number.php - PHP function to get ordinal number.
* Pass it a number and it will return the number suffixed with either
* of "st" (like 1st), "th" (like 4th), "nd" (like 2nd), "rd" (like 3rd).
* Copyright (C) 2016 Prabhas Gupte
*
* This is free script: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should also see <http://www.gnu.org/licenses/gpl.txt>
*/
function ordinal_number($number) {
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number % 100) >= 11 && ($number % 100) <= 13) {
$abbreviation = $number. 'th';
}
else {
$abbreviation = $number. $ends[$number % 10];
}
return $abbreviation;
} // ordinal_number
for($i=0; $i<20; $i++) {
echo '<br />' . ordinal_number($i);
}// for
?>

No comments:

Post a Comment