What are some best practices for handling user selections in dropdown menus using PHP to prevent unexpected behavior like the menu resetting to the default value?

When handling user selections in dropdown menus using PHP, it's important to ensure that the selected value is retained and not reset to the default value upon form submission or page reload. To prevent unexpected behavior, you can use PHP to check if a specific option is selected and then set the "selected" attribute accordingly in the HTML dropdown menu.

<select name="dropdown">
    <option value="option1" <?php if($_POST['dropdown'] == 'option1') echo 'selected'; ?>>Option 1</option>
    <option value="option2" <?php if($_POST['dropdown'] == 'option2') echo 'selected'; ?>>Option 2</option>
    <option value="option3" <?php if($_POST['dropdown'] == 'option3') echo 'selected'; ?>>Option 3</option>
</select>