php - how to set value to <select> tag [NOTE that the value may not always constant]
one text
Solution:
You need to build your option using array. Then, when you loop the options, you can compare with the answer, if match, set 'selected'.
<?php
$answer = "C"; // get from database this is just example
//need to build option in array, so that can make the comparison
$options = [
'A'=> 'A',
'B'=> 'B',
'C'=> 'C',
'D'=> 'D'
];
//build option html
$html_options = '';
foreach($options as $value => $label){
$selected = ($value == $answer) ? 'selected' : '';
$html_options .= "<option value='$value' $selected>$label</option>";
}
echo"
<label for='answer'> Answer :</label>
<select name='answer' id='answer'>$html_options</select>
";
?>
if you dont want using php to set value, then can use javascript to set as well
<?php
$answer = "C"; // get from database this is just example
echo"
<label for='answer'> Answer :</label>
<select name='answer' id='answer' value ='$answer'>
<option value='A'> A </option>
<option value='B'> B </option>
<option value='C'> C </option>
<option value='D'> D </option>
</select>
";
?>
<script
src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs="
crossorigin="anonymous"></script>
<script>
var ANSWER = '<?=$answer?>';
$(function(){
$('#answer').val(ANSWER)
})
</script>
Source