Generate A Select Box For A HTML Form

21st December 2007 - 2 minutes read time

Here is a function to generate a select box for a HTML form. The three parameters are:

  1. $name : The name of the select, this will appear in the "name" attribute.
  2. $options : An associative array containing all of the options.
  3. $default : The option that will be selected as default.
function generateSelect($name,$options,$default=''){
  $html = '<select name="'.$name.'">';
  foreach ($options as $value => $label) {
    $html .= '<option value="' . $value . '">' . $label . '</option>';
  }
  $html .= '</select>';
  return $html;
}

You can call the function like this:

echo generateSelect('selectPreference',array('yes'=>'yes','no'=>'no'),'yes');

Which produces the following HTML as output:

<select name="selectPreference"><option value="yes">yes</option><option value="no">no</option>
</select>

Comments

Permalink
this tag is very helpful to create a select box codings, thanks

paper cup machine (Sat, 04/13/2013 - 23:56)

Add new comment

The content of this field is kept private and will not be shown publicly.