Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: increment counter function using words (i.e. First, Second, Third, etc.. )

I've been trying to find a function which increments a counter using words. I know its possible using numbers with suffixes (i.e. 1st, 2nd, 3rd and so on). Here is a snippet of the code i've got:

function addOrdinalNumberSuffix($num) {
    if (!in_array(($num % 100),array(11,12,13))){
        switch ($num % 10) {
            // Handle 1st, 2nd, 3rd
            case 1:  return $num.'st';
            case 2:  return $num.'nd';
            case 3:  return $num.'rd';
        }
    }
    return $num.'th';
}

Code Source

But is there a way to replicate this with words (i.e First, Second, Third, etc..)?

I'd expect it to be quite difficult (but not impossible) to create an infinite counter, but anything up to 20 would suffice.

Any help would be much appreciated.

like image 738
VicePrez Avatar asked May 24 '11 19:05

VicePrez


1 Answers

A short little hack to accomplish the same result is (ab)using date() for it.

$num = 2;
echo date("jS", strtotime("January {$num}"));

// Output
"2nd"

Only works up to 31 though, and probably slower than just using an array like Parris suggested.

like image 181
Ludo - Off the record Avatar answered Oct 07 '22 00:10

Ludo - Off the record