What best practices should be followed when pre-selecting an option in a dropdown menu in PHP based on user input?

When pre-selecting an option in a dropdown menu in PHP based on user input, it is important to sanitize and validate the user input to prevent any security vulnerabilities. Once the user input is validated, you can compare it with the options in the dropdown menu and set the selected attribute for the matching option.

<?php
// User input
$user_input = $_POST['selected_option'];

// Sanitize and validate user input
$valid_options = ['option1', 'option2', 'option3'];
if(in_array($user_input, $valid_options)){
    // Pre-select the option in the dropdown menu
    echo '<select name="dropdown">';
    foreach($valid_options as $option){
        if($option == $user_input){
            echo '<option value="'.$option.'" selected>'.$option.'</option>';
        } else {
            echo '<option value="'.$option.'">'.$option.'</option>';
        }
    }
    echo '</select>';
} else {
    echo 'Invalid option selected';
}
?>