A A
RSS

Convert Month Name to Month Number in PHP

Thu, Oct 8, 2009

Tips

So I’ve been working on my tracking software, mainly the monthly reporting input for campaign statistics. One form uses an HTML select list that’s filled using a PHP array. While I loop through the array, I also select the current month for the user.

The issue I was having is that my database stores the month as its numerical value. I wanted to keep the month name in my select list, so I went in search of a solution. While it’s not hard, it did take some time to find. Here is the solution that worked for me:

// Setup month counter for loop
$mCounter=”1″; // Set month integer on January

// Build month array
$aMonths=array(”January”,”February”,”March”,”April”,”May”,”June”,”July”,”August”,
“September”,”October”,”November”,”December”);

// Loop through months
foreach($aMonths as $sMonth) {

// Convert month counter to month number
$iMonth=date(”m”, mktime(0,0,0,$mCounter,1,0));

// Select current month
if ($sMonth!=date(”F”)) {
$htmlMonths.=”<option value=\”".$iMonth.”\”>”.$sMonth.”</option>\n”;
} else {
$htmlMonths.=”<option value=\”".$iMonth.”\” selected>”.$sMonth.”</option>\n”;
}

// Update month counter
$mCounter++;
}

HTML code that displays the select:

<strong>Month</strong>:<br />
<select name=”selectMonth”><?php echo $htmlMonths; ?></select>

Your input and questions are always welcome!

Tags:

2 Responses to “Convert Month Name to Month Number in PHP”

  1. denny says:

    For your readers:

    for($i=1,$currMonth=date(’n');$i<13;$i++){
    $monthName=date(’F', mktime(0,0,0,$i,1,0));
    $bSelected=($currMonth!=$i)?”:’ selected’;
    $iMonth=str_pad($i,2,’0′,STR_PAD_LEFT);
    $htmlmonths.=”<option value=\”$iMonth\”$bSelected>$monthName</option>\n”;
    }

    This code is uglier but more efficient.

  2. Harder to read maybe, but much shorter. Thanks for the comment!

Leave a Reply

Advertise Here
Want Insider Tips and Exclusive Offers?
First Name
Email Address
Your information will not be sold
or shared with any third parties.
Advertise Here

Categories