How can you optimize the code to avoid repetition when pre-selecting options in a dropdown menu in PHP?

To avoid repetition when pre-selecting options in a dropdown menu in PHP, you can use a loop to iterate through the options and set the "selected" attribute for the option that matches the pre-selected value. This way, you can avoid writing repetitive code for each option.

<select name="dropdown">
    <?php
    $options = ['Option 1', 'Option 2', 'Option 3'];
    $preselected = 'Option 2'; // Set the pre-selected option here

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