Here is a sample code.
<?php $options = array('option1' => 'Option 1', 'option2' => 'Option 2', 'option3' => 'Option 3'); $myselect = 'option2'; ?> <select name="myselect"> <?php foreach($options as $key => $value) { echo sprintf('<option value="%s" %s>%s</option>', $key, $key == $myselect ? 'selected="selected"' : '', $value); } ?> </select>
If you regularly do such things, it is much more complicated in the function, or you can even create a helper class of the class.
The basic selection function is used here:
<?php function form_select($name, $options, $selected) { $html = sprintf('<select name="%s">', $name); foreach($options as $key => $value) { $html .= sprintf('<option value="%s"', $key); if ($selected == $key) $html .= ' selected="selected"'; $html .= sprintf('>%s</option>', $value); } $html .= '</select>'; return $html; }
Then you can create any selection just by calling:
echo form_select('myselect', $options, $selected);
You can easily force a function to handle additional attributes such as style, class, and identifier.
Jacob
source share