daily pastebin goal
49%
SHARE
TWEET

Dynamic HTML Select generation in PHP

tamouse Aug 24th, 2012 24 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Return an HTML <select> statment based on an array of options
  3.  *
  4.  * @returns string HTML output for select statement
  5.  * @author Tamara Temple <tamara@tamaratemple.com>
  6.  * @param array $options_array - array of options (return value => option string),
  7.  * @param string $element_name - name and id of the select statement
  8.  * @param string $label=null - label to be used for select statement
  9.  * @param string $selected_item=null - key in $options_array to be preselected
  10.  **/
  11. function dynamic_select ($options_array,
  12.                          $element_name,
  13.                          $label=null,
  14.                          $selected_item=null)
  15. {
  16.   $out = PHP_EOL;
  17.   if (!empty($label)) $out .= "<label for \"$element_name\">$label</label>".PHP_EOL;
  18.   $out .= "<select name=\"$element_name\" id=\"$element_name\">".PHP_EOL;
  19.   foreach ($options_array as $key => $value) {
  20.     $out .= "  <option value=\"$key\"";
  21.     if ($key == $selected_item) $out .= " selected=\"selected\"";
  22.     $out .= ">$value</option>".PHP_EOL;
  23.   }
  24.   $out .= "</select>".PHP_EOL;
  25.   return $out;
  26. } // END function dynamic_select
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top