How can if-conditions be effectively used within a while loop in PHP to solve issues related to retaining selected options in a dropdown menu?

When using a dropdown menu within a form in PHP, if-conditions can be used within a while loop to check and retain the selected option based on the user's previous selection. By comparing the current option with the previously selected option, the code can set the 'selected' attribute for the correct option. This ensures that the dropdown menu retains the user's choice even after form submission.

<select name="dropdown">
    <?php
    $options = array("Option 1", "Option 2", "Option 3");
    $selected_option = isset($_POST['dropdown']) ? $_POST['dropdown'] : '';

    foreach($options as $option) {
        echo '<option value="' . $option . '"';
        if($option == $selected_option) {
            echo ' selected';
        }
        echo '>' . $option . '</option>';
    }
    ?>
</select>