What are some common pitfalls when preselecting options in a dynamic SELECT dropdown in PHP?

One common pitfall when preselecting options in a dynamic SELECT dropdown in PHP is not properly checking if the selected value matches any of the options in the dropdown. To solve this, you should iterate through the options and add the 'selected' attribute to the option that matches the selected value.

<select name="dynamic_select">
    <?php
    $options = ['Option 1', 'Option 2', 'Option 3'];
    $selected_value = 'Option 2'; // Value to preselect

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