Easily generate a month select box in PHP

Having a drop down menu for month selection is a relatively common need, but it can be a pain to write from scratch each time. Here’s a short snippet that will generate a select input (drop down menu) for all 12 months of the year – the option values will be the month numbers with leading zeros:

<?php
function month_select_box( $field_name = 'month' ) {
$month_options = '';
for( $i = 1; $i <= 12; $i++ ) {
$month_num = str_pad( $i, 2, 0, STR_PAD_LEFT );
$month_name = date( 'F', mktime( 0, 0, 0, $i + 1, 0, 0, 0 ) );
$month_options .= '<option value="' . esc_attr( $month_num ) . '">' . $month_name . '</option>';
}
return '<select name="' . $field_name . '">' . $month_options . '</select>';
}
?>

view raw
function.php
hosted with ❤ by GitHub

To remove the leading zeros, simply remove the line with the str_pad() function.

Leave a Reply