Generate A Select Box For A HTML Form

21st December 2007 - 1 minute 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.
  1. function generateSelect($name,$options,$default=''){
  2. $html = '<select name="'.$name.'">';
  3. foreach ($options as $value => $label) {
  4. $html .= '<option value="' . $value . '">' . $label . '</option>';
  5. }
  6. $html .= '</select>';
  7. return $html;
  8. }

You can call the function like this:

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

Which produces the following HTML as output:

  1. <select name="selectPreference"><option value="yes">yes</option><option value="no">no</option>
  2. </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.