create / expand a select menu while using an array dynamically


PHP form select menu ver. 1.02

updated: 2006-02-12
In a lot of dynamic forms or content management sytems the form element "SELECT" is used frequently. If you use your PHP code inside the standard HTML element the code will be nearly unreadable. Adding extra options is not really fun. This small handy function will produce a select based on an associative array. Just define an array and call the function, that's all. Now XHTML valid!

Viewed 31268 times

Rating: script rated with stars
 

Your banner at finalwebsites.com?
use the contact form for further information and prices.

<?php
// build here the array with values for the select,
// notice that the array key is used option value and the array value as the label.
$test_array = array("var_1"=>"first label", "some_var"=>"it's hot", "last_constant"=>"last element");

// the properties of this function the array above, the name of the select menu and the initial value.
// If the initial value is empty (by default the an empty option is added otherwise.
// Use only a valid key from the above array as initial value and the selected state is used for this value.
// New in version 1.01 the label property.
// New in version 1.02 replaced the "!isset" test with an "empty" and the menu is XHTML valid now
function dynamic_select($the_array, $element_name, $label, $init_value = "") {
    $menu = ($label != "") ? "<label for=\"".$element_name."\">".$label."</label>\n" : "";
    $menu .= "<select name=\"".$element_name."\" id=\"".$element_name."\">\n";
    if (empty($_REQUEST[$element_name])) {
        if ($init_value == "") {
            $menu .= "  <option value=\"\">...</option>\n";
             $curr_val = "";
        } else {
            $curr_val = $init_value;
        }
    } else {
        $curr_val = $_REQUEST[$element_name];
    }
    foreach ($the_array as $key => $value) {
        $menu .= "  <option value=\"".$key."\"";
        $menu .= ($key == $curr_val) ? " selected>" : ">";
        $menu .= $value."</option>\n";
    }
    $menu .= "</select>\n";
    return $menu;
}
/* Example:
echo create_select($test_array, "test_menu", "my label", "some_var");

will output this:
<label for="test_menu">my label</label>
<select name="test_menu">
  <option value="var_1">first label
  <option value="some_var" selected>it's hot
  <option value="last_constant">last element
</select>
*/

?>