Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...