What are best practices for maintaining user selections in select fields before form submission in PHP?

When a form is submitted in PHP, the user's selections in select fields may not be maintained if the page is refreshed or if there are validation errors. To maintain these selections, you can store the selected values in session variables before the form is submitted, and then repopulate the select fields with these values after the form is submitted.

// Start session
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store select field values in session variables
    $_SESSION['select_field'] = $_POST['select_field'];
} else {
    // Check if session variable exists and repopulate select field
    $selected_option = isset($_SESSION['select_field']) ? $_SESSION['select_field'] : '';
}

// HTML form with select field
echo '<form method="post">';
echo '<select name="select_field">';
echo '<option value="option1"'.($selected_option == 'option1' ? ' selected' : '').'>Option 1</option>';
echo '<option value="option2"'.($selected_option == 'option2' ? ' selected' : '').'>Option 2</option>';
echo '</select>';
echo '<input type="submit" value="Submit">';
echo '</form>';