How can PHP be used to maintain selected options in dropdown menus after form submission for a better user experience?
When a form is submitted with selected options in dropdown menus, PHP can be used to store the selected values in variables and then set the "selected" attribute in the HTML dropdown options to maintain the selected options after form submission. This helps provide a better user experience by retaining the user's selections.
<?php
// Assume form submission with selected option values
$selectedOption1 = $_POST['dropdown1'] ?? '';
$selectedOption2 = $_POST['dropdown2'] ?? '';
?>
<select name="dropdown1">
<option value="option1" <?php echo ($selectedOption1 == 'option1') ? 'selected' : ''; ?>>Option 1</option>
<option value="option2" <?php echo ($selectedOption1 == 'option2') ? 'selected' : ''; ?>>Option 2</option>
<option value="option3" <?php echo ($selectedOption1 == 'option3') ? 'selected' : ''; ?>>Option 3</option>
</select>
<select name="dropdown2">
<option value="optionA" <?php echo ($selectedOption2 == 'optionA') ? 'selected' : ''; ?>>Option A</option>
<option value="optionB" <?php echo ($selectedOption2 == 'optionB') ? 'selected' : ''; ?>>Option B</option>
<option value="optionC" <?php echo ($selectedOption2 == 'optionC') ? 'selected' : ''; ?>>Option C</option>
</select>