Related Posts

Archive

Ordinal Suffixes and PHP’s Switch Statement

July 1st, 2008

I had a integer I wanted to suffix - 1st, 2nd, 13011th, and so on.

So, I saw This code. And it was a lot of code for a simple problem.

So I wrote somthing shorter.

echo " the {$count}";
 
switch ( $count ) {
case ($count % 10 == 1 && $count % 100 != 11 ): echo "st"; break;
case ($count % 10 == 2 && $count % 100 != 12 ): echo "nd"; break;
case ($count % 10 == 3 && $count % 100 != 13 ): echo "rd"; break;
case "0":
case 0: echo " lack"; break;
default: echo "th"; break;
}
 
echo " of whatever";

Most of the time in PHP, I’ve used the case statement for simple comparison; if $count = 1, do this, if $count = 2, do that, and so on. Here I am using its full capacity for logic; all this can be written as if..else statements. If not for the option of zero, I could have used switch(true).

-Sud.

You can, of course, put this in a function.

Posted in PHP, Technical |

Comments are closed.

Previous post: Microsoft Access MDB to Ruby Hash

Next Post: Runic Transliteration