Convert Month Name to Month Number in PHP
Thu, Oct 8, 2009
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: php







For your readers:
This code is uglier but more efficient.
Harder to read maybe, but much shorter. Thanks for the comment!