Here is a function from CodeIgniter's helpers.
function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
{
if ( ! is_array($selected))
{
$selected = array($selected);
}
// If no selected state was submitted we will attempt to set it automatically
if (count($selected) === 0)
{
// If the form name appears in the $_POST array we have a winner!
if (isset($_POST[$name]))
{
$selected = array($_POST[$name]);
}
}
if ($extra != '') $extra = ' '.$extra;
$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';
$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
foreach ($options as $key => $val)
{
$key = (string) $key;
$val = (string) $val;
$sel = (in_array($key, $selected))?' selected="selected"':'';
$form .= '<option value="'.$key.'"'.$sel.'>'.$val."</option>\n";
}
$form .= '</select>';
return $form;
}
To call it you'd do something like the following;
// example of submit
if (isset($_POST['submit']))
{
$default = $_POST['month'];
}
$options = array(
'january' => 'January',
'february' => 'February',
'march' => 'March',
'april' => 'April',
'may' => 'May',
'june' => 'June',
'july' => 'July',
'august' => 'August',
'september' => 'September',
'october' => 'October',
'november' => 'November',
'december' => 'December'
);
form_dropdown('month', $options, $default);
This is going to produce (assuming form is submitted with the value as "march" and comes back);
<select name="month">
<option value="january">January</option>
<option value="february">February</option>
<option value="march" selected="selected">March</option>
// etc
</select>