Dynamic select menu
In dynamic forms or content management sytems the form element “SELECT” is used frequently. If we use PHP code inside the standard HTML element the code will be nearly unreadable. This function will produce a select based on an associative array. We can just define an array and call the function.
<?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 name”, “some_var”=>”second label”, “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.
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 dynamic_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 name
<option value=”some_var” selected>second label
<option value=”last_constant”>last element
</select>
*/
?>
