What are the best practices for handling dropdown selections in PHP to ensure all options are displayed correctly?

When handling dropdown selections in PHP, it is important to ensure that all options are displayed correctly by populating the dropdown menu with the available options and selecting the appropriate option based on the user's input. To achieve this, you can use a foreach loop to iterate through the options and compare each option with the selected value to determine which option should be marked as selected.

<select name="dropdown">
    <?php
    $options = array("Option 1", "Option 2", "Option 3");
    $selected = "Option 2"; // User's selected option
    
    foreach($options as $option) {
        if($option == $selected) {
            echo "<option value='$option' selected>$option</option>";
        } else {
            echo "<option value='$option'>$option</option>";
        }
    }
    ?>
</select>