PHP code to add st, nd, rd or th to a number
Pete Donnell — Wed, 02/03/2010 - 11:42
This one's short and sweet: while working on a PHP application I needed to format some numbers as text so that, for example, '1' became '1st', '13' became '13th', '22' became '22nd' and so on. There isn't a built-in PHP function to do this (as far as I know) and none of the code snippets I came across online were very neat, so I ended up writing my own function. Since it's something that I imagine gets used a lot, I thought I'd put it up here. I am releasing it into the public domain so everyone is free to use the code however they wish, although some acknowledgement or feedback if it's been useful to you would be appreciated!
<?php
function ordinal($input_number)
{
$number = (string) $input_number;
$last_digit = substr($number, -1);
$second_last_digit = substr($number, -2, 1);
$suffix = 'th';
if ($second_last_digit != '1')
{
switch ($last_digit)
{
case '1':
$suffix = 'st';
break;
case '2':
$suffix = 'nd';
break;
case '3':
$suffix = 'rd';
break;
default:
break;
}
}
return $number.$suffix;
}
?>














Slight Optimisation?
Anonymous — Tue, 04/27/2010 - 20:35Instead of breaking out on the switch-case, could you just return with the literal concatenated instead, as shown below:
<?php function ordinal($input_number) { $number = (string) $input_number; $last_digit = substr($number, -1); $second_last_digit = substr($number, -2, 1); if ($second_last_digit != '1') { switch ($last_digit) { case '1': return $number.'st'; case '2': return $number.'nd'; case '3': return $number.'rd'; default: return $number.'th'; } } else { return $number.'th'; } } ?>JavaScript to show when a page was last updated
Pete Donnell — Tue, 03/16/2010 - 17:06Here's a similar snippet of code, this time in JavaScript, which will output the date that a page was last modified in human readable format. See http://www.kitserve.org.uk/pete/ with JavaScript enabled for an example of it in use. Note that the suffix is only correctly generated for numbers less than 100, for example '111' would be turned into '111st'! This isn't a problem for dates, of course, but you'll want to bear it in mind if you're using the code for more general numbers. Generalising the code to fix this issue would be trivial, for example by adding something along the lines of
and changing the
ifandswitchstatements to operate onnum_remainderinstead ofday.Alternatively, you can copy the code from http://www.kitserve.org.uk/pete/scripts/lastupdate.js - please don't hotlink to it, if you want to use the code on one of your own sites copy the .js file across. As with the PHP example above, any comments are welcomed.