Generate A Select Box For A HTML Form

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>


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

Add new comment

The content of this field is kept private and will not be shown publicly.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
1 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.