Create month and year dropdown list in php

Create month and year dropdown list in php

We can simply create month and year dropdown in php with the help of arrays. Below is the code snippet which you can use in your ongoing project.

Creating Year drop down list
All you need to do is create a for loop with starting year and ending year as parameter and print the required options inside the loop.

<select name="year">
<option value="">Select Year</option>
<?php
for ($year = 2018; $year <= 2030; $year++) {
$selected = (isset($getYear) && $getYear == $year) ? 'selected' : '';
echo "<option value=$year $selected>$year</option>";
}
?>
</select>

Creating Month drop down list
In order to create the drop-down, First define an array variable to store the month list. And then loop over the array and print the month drop down.

<?php
$MonthArray = 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",
);
?>
<select name="month">
<option value="">Select Month</option>
<?php
foreach ($MonthArray as $monthNum=>$month) {
$selected = (isset($getMonth) && $getMonth == $monthNum) ? 'selected' : '';
//Uncomment line below if you want to prefix the month number with leading 0 'Zero'
//$monthNum = str_pad($monthNum, 2, "0", STR_PAD_LEFT);
echo '<option ' . $selected . ' value="' . $monthNum . '">' . $month . '</option>';
}
?>
</select>

One Reply to “Create month and year dropdown list in php”

Leave a Reply

Your email address will not be published. Required fields are marked *