How can the selected option in a dropdown menu be highlighted or selected automatically after a page refresh in PHP?

When a page is refreshed, the selected option in a dropdown menu is not automatically highlighted. To solve this issue, you can use PHP to store the selected option in a session variable and then use JavaScript to set the selected attribute of the dropdown option.

<?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 session variable
function isSelected($value) {
    if (isset($_SESSION['selected_option']) && $_SESSION['selected_option'] == $value) {
        echo 'selected';
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dropdown Menu</title>
</head>
<body>
    <form method="post">
        <select name="dropdown">
            <option value="option1" <?php isSelected('option1'); ?>>Option 1</option>
            <option value="option2" <?php isSelected('option2'); ?>>Option 2</option>
            <option value="option3" <?php isSelected('option3'); ?>>Option 3</option>
        </select>
        <input type="submit" value="Submit">
    </form>
</body>
</html>