How can HTML attribute values affect the display of data passed from a PHP array in a select command?

HTML attribute values can affect the display of data passed from a PHP array in a select command by specifying the selected attribute for the option that should be pre-selected. This can be achieved by comparing the current array value with the selected value and adding the selected attribute if they match. By dynamically generating the select options with the correct selected attribute, the desired option will be displayed as pre-selected.

<select name="example">
    <?php
    $options = array("Option 1", "Option 2", "Option 3");
    $selected = "Option 2"; // Value to be pre-selected
    
    foreach($options as $option) {
        if($option == $selected) {
            echo "<option value='$option' selected>$option</option>";
        } else {
            echo "<option value='$option'>$option</option>";
        }
    }
    ?>
</select>