views:

156

answers:

3

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 within each option?

A: 
<?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>';
}

?>
Sjoerd
A: 

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.) :-)

middaparka
A: 

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>';
Veger