Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP given a month string such as "November" how can I return 11 without using a 12 part switch statement?

Tags:

date

php

mktime

I.e.

Month        Returns
January      1
February     2
March        3
April        4
May          5
June         6
July         7
August       8
September    9
October      10
November     11
December     12

I've seen examples using mktime when given the number of the month and returning the month string, but not the reverse.

like image 454
stormist Avatar asked Apr 23 '10 20:04

stormist


3 Answers

Try

echo date('n', strtotime('November')); // returns 11

If you have to do this often, you might consider using an array that has these values hardcoded:

$months = array( 1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
                 5 => 'May',     6 => 'June',     7 => 'July',  8 => 'August',
                 9 => 'September', 10 => 'October', 11 => 'November',
                 12 => 'December');

Can also do it the other way round though, using the names for the keys and numbers for values.

With the names for values you do

echo array_search('November', $months); // returns 11

and with names for keys you do

echo $months['November']; // returns 11

I find using the numbers for the keys somewhat better in general, though for your UseCase the names for keys approach is likely more comfortable. With just 12 values in the array, there shouldn't be much of a difference between the array approches.

A quick benchmark noted a difference of 0.000003s vs 0.000002s, whereas the time conversion takes 0.000060s on my computer (read: might differ on other computer).

like image 78
Gordon Avatar answered Oct 21 '22 03:10

Gordon


What about using strtotime() to convert November to a timestamp, and, then, the date() function with the n format to get the corresponding number :

$ts = strtotime('november');
echo date('n', $ts);

Gives the following output :

11


And, just for fun, a portion of code such as the following one :

$months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', );
foreach ($months as $m) {
    $ts = strtotime($m);
    echo $m . ' : ' . date('n', $ts) . '<br />';
}

will give you the list of all month with their corresponding numbers -- showing that this idea will work for all 12 months, and not only November ;-)

like image 25
Pascal MARTIN Avatar answered Oct 21 '22 03:10

Pascal MARTIN


I can't imagine this is more efficient, but it works

$t = strtotime("March");
echo date('n',$t);
like image 33
Fletcher Moore Avatar answered Oct 21 '22 01:10

Fletcher Moore