How can conditional statements be used within a PHP while loop to achieve the desired pre-selection of a value in a select box?

To pre-select a value in a select box within a PHP while loop, you can use conditional statements to check if the current value matches the desired pre-selected value. If it does, you can add the 'selected' attribute to that option tag. This way, the desired value will be pre-selected in the select box when the page loads.

<select name="options">
<?php
$desired_value = "Option 2"; // Desired pre-selected value
$options = array("Option 1", "Option 2", "Option 3");

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