What is the correct syntax for displaying selected options in a multiple selection menu using PHP?

When displaying selected options in a multiple selection menu using PHP, you need to loop through each option and check if it should be selected based on the user's input. You can achieve this by using the 'selected' attribute in the HTML option tag for each option that should be pre-selected.

<select name="options[]" multiple>
    <?php
    $selectedOptions = array(1, 3); // Example array of selected option values
    $options = array(1, 2, 3, 4, 5); // Example array of all options

    foreach ($options as $option) {
        $selected = (in_array($option, $selectedOptions)) ? 'selected' : '';
        echo "<option value='$option' $selected>Option $option</option>";
    }
    ?>
</select>