Tales of an IT Nobody

devbox:~$ iptables -A OUTPUT -j DROP

Add “th” (“nd”, “st”) to a number … painlessly. April 25, 2011

There’s not enough out there about this trick – but you don’t need a convoluted solution to add rank indicators to a number, so to add more noise to google search, here my variant is:

Make sure you visit part 2!

Logical breakdown:

First we get mod of $n against 10 – essentially stripping away base 10 from rolling over.

Then, since we word 1 = 1st, 2 = 2nd, 3 = 3rd – see if we have to do anything special for numbers with modulo in that range – otherwise anything from 4-9,0 is nth.

Additionally, we take characters in the ‘eleventh’ verbal range and simply make them all ‘nth’ – so we skip our special date logic and cut straight to $n.’th’.

We check this by sloppily looking for the 2nd to the last character of our number using substr. If it is NOT 1 (Indicating an ‘eleventh’) – we take the logic block for using date to deal with the markup (st, nd, rd)

The only exception to all of this is the substr will wrap the number ‘1’ and take the logic, so we make sure that if it’s explicit value is 1 – we take the logic as well to indicate ‘1st’….

In hindsight… I will expand on whether or not using date() + mktime() is worth it versus the extra effort for manually figuring the st/nd/rd suffixes.

Follow up: I have made a new rendition with speed comparisons

Categories: php programming

Leave a Reply

Your email address will not be published. Required fields are marked *