How can PHP be used to prepopulate selected options in a multiple select field?

To prepopulate selected options in a multiple select field using PHP, you can use a loop to iterate through the options and add the "selected" attribute to the ones that match the values you want to prepopulate. This can be done by checking if the option value is in an array of selected values.

<select name="options[]" multiple>
    <?php
    $selectedValues = array('value1', 'value2'); // Values to prepopulate
    $options = array('value1', 'value2', 'value3', 'value4'); // All available options
    
    foreach ($options as $option) {
        $selected = (in_array($option, $selectedValues)) ? 'selected' : '';
        echo "<option value='$option' $selected>$option</option>";
    }
    ?>
</select>