What are some best practices for selecting default values in a dropdown menu in PHP?

When selecting default values in a dropdown menu in PHP, it's important to ensure that the default value is valid and corresponds to one of the options in the dropdown. One way to handle this is by checking if the default value exists in the list of options before setting it as selected. Additionally, you can use a conditional statement to determine which option should be selected based on a specific condition.

<select name="dropdown">
    <?php
    $options = ['Option 1', 'Option 2', 'Option 3'];
    $defaultValue = 'Option 2';

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