I found that I was looking for this to see if there is a better way to do this.
The best and clean answer is from @roryf, however, if you don't loop your data, I thought it would be much cleaner to wrap it with a function:
function set_selected($desired_value, $new_value)
{
if($desired_value==$new_value)
{
echo ' selected="selected"';
}
}
Then you will use it as follows:
<?php $selected_value = 2; ?>
<select>
<option value="1"<?php set_selected('1', $selected_value); ?>> Volvo </option>
<option value="2"<?php set_selected('2', $selected_value); ?>> Saab </option>
<option value="3"<?php set_selected('3', $selected_value); ?>> Mercedes </option>
<option value="4"<?php set_selected('4', $selected_value); ?>> Audi </option>
</select>
This would set Saab as the chosen one :)
source
share