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

前端 未结 6 1048
攒了一身酷
攒了一身酷 2020-12-06 12:20

I.e.

Month        Returns
January      1
February     2
March        3
April        4
May          5
June         6
July         7
August       8
September           


        
6条回答
  •  暖寄归人
    2020-12-06 13:13

    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) . '
    '; }

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

提交回复
热议问题