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

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).

Leave a Comment