19.3 Generating <select> Lists
TechniqueUse a while loop to loop through your array and print out the <option> tags: <?php print "<select name=\"select_list\">"; foreach ($select_array as $name => $value) { print "<option value=\"$value\">$name</option>\n"; } print "</select>"; ?> CommentsIn PHP, as shown next in recipe 19.4, you can generate JavaScript and HTML with extraordinary ease. One use is generating <select> lists from an associative array. Using this basic theory, you can also generate tables, lists, and even entire Web pages ”it just takes a little creativity. The preceding example will suffice for simple needs, but here is a useful function that does the same thing and a lot more: <?php function html_options($output, $values = NULL, $selected = NULL, $first_option_output = false) { // If there is nothing to output, return if (empty($output)) return; // Cast all arguments to arrays settype($values, "array"); settype($output, "array"); settype($selected, "array"); // Count the number of values in arrays $num_output = count($output); $num_values = count($values); $html_output = ""; if ($first_option_output) { $html_output = "<OPTION value=\"\">"; $html_output .= "$first_option_output</OPTION>\n"; } for ($i=0; $i < $num_output; $i++) { // By default, check value against $selected $sel_check = $values[$i]; $html_output .= "<OPTION"; if ($i < $num_values) { $html_output .= " value=\"".$values[$i]."\""; } else { // If more output than values, check // output against $selected. $sel_check = $output[$i]; } if (in_array($sel_check, $selected)) { $html_output .= " selected"; } $html_output .= ">".$output[$i]."</OPTION>\n"; } return($html_output); } ?> The first argument to this function is a list of strings you want to display in the select box. That's all that's really needed sometimes. The second argument is a list of option values ”one for each string. The third argument enables you to select a certain option automatically when it displays on the page. Finally, your first option string will very often be something like "--select month--" . The last argument enables you to pass that string to be displayed as the first option. Here is an example of using this function with all the arguments: <?php $colors = array("Red", "Green", "Blue", "Orange"); $color_values = array("#ff0000", "#00ff00", "#0000ff", "#ff8000"); $selected_color = "#ff8000"; print html_options($colors, $color_values, $selected_color, "-- select color --"); ?> This would output the following HTML: <OPTION value="">-- select color --</OPTION> <OPTION value="#ff0000">Red</OPTION> <OPTION value="#00ff00">Green</OPTION> <OPTION value="#0000ff">Blue</OPTION> <OPTION value="#ff8000" selected>Orange</OPTION> |