Are there any best practices for handling preselected options in dynamically generated SELECT dropdowns in PHP?

When dynamically generating SELECT dropdowns in PHP, it is common to have preselected options based on certain conditions. One way to handle this is by checking each option against a variable that determines the selected value, and adding the 'selected' attribute to the option that matches. This can be achieved using a foreach loop to iterate through the options and an if statement to check for the selected value.

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