How can PHP be used to dynamically set the selected attribute for different options in a Select Box based on user input?

To dynamically set the selected attribute for different options in a Select Box based on user input, you can use PHP to check the user input against each option value and add the 'selected' attribute to the matching option. This can be achieved by using a loop to iterate through the options and comparing the user input with each option value.

<select name="options">
    <?php
    $userInput = $_POST['user_input']; // Assuming user input is submitted via a form
    $options = ['Option 1', 'Option 2', 'Option 3']; // Array of options
    
    foreach ($options as $option) {
        if ($userInput == $option) {
            echo "<option value='$option' selected>$option</option>";
        } else {
            echo "<option value='$option'>$option</option>";
        }
    }
    ?>
</select>