PHPRO.ORG

This helper function is ideal for any script where you need to produce a dropdown menu for months. The function will default to the current month for the selectec item, or can be set to any month you like.

Two versions of this function are provided. They are identical with the exception of the second, longer, version uses and array of months, rather than calling strtotime. The reason for this is the gain in speed that is afforded by using an array. The speed of each follows

  1. 0.00197291374207
  2. 0.000170946121216

This is a saving of 0.001801967620854 seconds. Some may say it is a moral victory at best, those keen on optimazation may consider it crucial. To this end, PHPRO.ORG provides a choice.

Using mktime


<?php

/*
 *
 * @Create an HTML drop down menu
 *
 * @param string $name The element name and ID
 *
 * @param int $selected The month to be selected
 *
 * @return string
 *
 */
function monthDropdown($name="month"$selected=null)
{
        
$dd '<select name="'.$name.'" id="'.$name.'">';

        
/*** the current month ***/
        
$selected is_null($selected) ? date('n'time()) : $selected;

        for (
$i 1$i <= 12$i++)
        {
                
$dd .= '<option value="'.$i.'"';
                if (
$i == $selected)
                {
                        
$dd .= ' selected';
                }
                
/*** get the month ***/
                
$mon date("F"mktime(000$i+1000));
                
$dd .= '>'.$mon.'</option>';
        }
        
$dd .= '</select>';
        return 
$dd;
}

/*** example usage ***/
$name 'my_dropdown';
$month 10;

echo 
monthDropdown($name$month);

?>

Using an array of months


<?php

/*
 *
 * @Create an HTML drop down menu
 *
 * @param string $name The element name and ID
 *
 * @param int $selected The month to be selected
 *
 * @return string
 *
 */
function monthDropdown($name="month"$selected=null)
{
        
$dd '<select name="'.$name.'" id="'.$name.'">';

        
$months = array(
                
=> 'january',
                
=> 'february',
                
=> 'march',
                
=> 'april',
                
=> 'may',
                
=> 'june',
                
=> 'july',
                
=> 'august',
                
=> 'september',
                
10 => 'october',
                
11 => 'november',
                
12 => 'december');
        
/*** the current month ***/
        
$selected is_null($selected) ? date('n'time()) : $selected;

        for (
$i 1$i <= 12$i++)
        {
                
$dd .= '<option value="'.$i.'"';
                if (
$i == $selected)
                {
                        
$dd .= ' selected';
                }
                
/*** get the month ***/
                
$dd .= '>'.$months[$i].'</option>';
        }
        
$dd .= '</select>';
        return 
$dd;
}


/*** example usage ***/
$name 'my_dropdown';
$month 9;

echo 
monthDropdown($name$month);

?>

Demonstration