What are some best practices for dynamically selecting an option in a select box based on a PHP variable in a web application?

When dynamically selecting an option in a select box based on a PHP variable, you can achieve this by using a loop to iterate through the options and adding the 'selected' attribute to the option that matches the PHP variable.

<select name="selectBox">
    <?php
    $options = array("Option 1", "Option 2", "Option 3");
    $selectedOption = "Option 2"; // PHP variable to select a specific option

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