开发者

Simple way to select chosen option in <select> from the value given by $_POST?

开发者 https://www.devze.com 2022-12-16 19:48 出处:网络
How can i add the selected=\"selected\" bit to the option in an HTML <select> input from the sent $_POST data without an if statement w开发者_C百科ithin each option?<?php

How can i add the selected="selected" bit to the option in an HTML <select> input from the sent $_POST data without an if statement w开发者_C百科ithin each option?


<?php

$options = array(1 => 'Banana', 2 => 'Apple');

foreach ($options as $key => $value) {
    echo '<option value=""';
    if ($key == $_POST['fruit']) echo ' selected="selected"';
    echo '>'.$value.'</option>';
}

?>


Programatically, you could do it like this:

$optionNames = array('This', 'Is', 'A', 'Test');
echo '<select id="testselect" name="testselect">';
foreach($optionNames as $currentOption) {
    echo '<option value="'.$currentOption.'"';
    echo $_POST['testselect'] == $currentOption ? ' selected="selected"' : '';
    echo '>'.$currentOption.'</option>';
}
echo '</select>';

Must confess I don't have a dev box up at the moment to test the above code, but it should be OK. (Apologies if not.) :-)


I suppose using an if statement for each option is most efficient.

But you can create an array containing empty strings except for the location of the option you want to select in order to eliminate the if statement.

$options = array(1 => 'Banana', 2 => 'Apple', 3 => 'Orange');
$selected_options = array_fill(1, sizeof($options), "");
if(array_key_exists($_POST['fruit'], $options))
    $selected_options[$_POST['fruit']] = " selected=\"selected\"";

echo '<select id="fruit" name="fruit">';
foreach($options as $optionId => $optionText)
    echo '<option value="'.$optionId.'"'.$selected_options[$optionId].'>'.$optionText.'</option>';
echo '</select>';
0

精彩评论

暂无评论...
验证码 换一张
取 消