What are some common methods for retaining user-selected options in dropdown lists when reloading a page in PHP?

When a user selects an option from a dropdown list on a webpage and the page is reloaded, the selected option is typically not retained by default. To retain the user-selected option, you can use PHP to store the selected value in a session variable and then set the selected attribute in the HTML dropdown list based on the stored value.

<?php
session_start();

// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $_SESSION['selected_option'] = $_POST['dropdown'];
}

// Set the selected attribute based on the stored value
function isSelected($value) {
    if (isset($_SESSION['selected_option']) && $_SESSION['selected_option'] == $value) {
        return 'selected';
    }
}

?>

<select name="dropdown">
    <option value="option1" <?php echo isSelected('option1'); ?>>Option 1</option>
    <option value="option2" <?php echo isSelected('option2'); ?>>Option 2</option>
    <option value="option3" <?php echo isSelected('option3'); ?>>Option 3</option>
</select>