I made this one
The first argument is the array.
The second argument is an array of attributes such as your form name, id or class.
The third argument is for when you have multidimensional array such as one you'd get back from an sql result, it should have two subsets, one with the key 'value' and the other keyed as 'option'. This allows you to set what should be enclosed in the option tag and what should be the value for that option.
Lastly we have the fourth parameter which basically adds the 'selected' tag in the option with a value of $selected or where the element's key is equals to $selected
.
function array_to_drop_down($array, $attributes=false /*array('attr_1' => 'value')*/, $kv=false /* array('value' => 'key1', 'option' => 'key2')*/, $selected=false )
{
$html_data = "<select ";
if ( $attributes != false && is_array($attributes) )
{
foreach ( $attributes as $name => $value )
{
$html_data .= " {$name}=\"{$value}\" ";
}
}
$html_data .= '>';
foreach( $array as $key => $option )
{
$select_html = '';
if( $selected != false )
{
if( ($kv && $selected == $option[$kv['value']]) )
{
$select_html = 'selected="selected"';
}
elseif ( $selected == $key && ! is_array($option) )
{
$select_html = 'selected="selected"';
}
}
if ( $kv == false )
{$html_data .= "<option {$select_html} value=\"{$key}\">{$option}</option>";}
else
{$html_data .= "<option {$select_html} value=\"{$option[$kv['value']]}\">{$option[$kv['option']]}</option>";}
}
return $html_data . "</select>";
}
Here it is when it's called:
$array = array('Apple', 'Banana', 'Watermelon');
array_to_drop_down($array, array('name' => 'my_form'), false, 1);
This should render the following HTML:
<select name="my_form" >
<option value="0">Apple</option>
<option selected="selected" value="1">Banana</option>
<option value="2">Watermelon</option>
</select>
Here is another example with a two dimensional array:
$array = array(
array('name' => 'John', 'student_id' => 1234),
array('name' => 'Jen', 'student_id' => 5678),
array('name' => 'Sally', 'student_id' => 9012)
);
array_to_drop_down( $array,
array('name' => 'my_form', 'id' => 'the_form_id'),
array('option' => 'name', 'value' => 'age'), 1);
We've asked the function to select where the option's value is 5678, this should output
<select name="my_form" id="the_form_id" >
<option value="1234">John</option>
<option selected="selected" value="5678">Jen</option>
<option value="9012">Sally</option>
</select>
Looks a little long to set up but if you're going to be repeating this kind of thing many times it will look neater on your code rather than a bunch of foreach loops to create the form yourself