How can a pre-selected value be marked in a dynamic select form field using PHP?
To mark a pre-selected value in a dynamic select form field using PHP, you can check if the value matches the pre-selected value and add the 'selected' attribute to the option tag. This will ensure that the correct option is displayed as selected when the form is rendered.
<select name="dynamic_select">
<?php
$pre_selected_value = "Option 2"; // Pre-selected value
$options = array("Option 1", "Option 2", "Option 3"); // Dynamic options
foreach ($options as $option) {
if ($option == $pre_selected_value) {
echo "<option value='$option' selected>$option</option>";
} else {
echo "<option value='$option'>$option</option>";
}
}
?>
</select>