What is the best practice for handling color selection in a form within a PHP session?

When handling color selection in a form within a PHP session, it is best practice to store the selected color in the session variable to persist it across different pages or form submissions. This ensures that the selected color remains selected until the user changes it or the session expires.

<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $_SESSION['selected_color'] = $_POST['color'];
}

// Retrieve the selected color from the session (if set)
$selected_color = isset($_SESSION['selected_color']) ? $_SESSION['selected_color'] : '';

// Display the form with the selected color pre-selected
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <label for="color">Select a color:</label>
    <select name="color" id="color">
        <option value="red" <?php if ($selected_color == 'red') echo 'selected'; ?>>Red</option>
        <option value="blue" <?php if ($selected_color == 'blue') echo 'selected'; ?>>Blue</option>
        <option value="green" <?php if ($selected_color == 'green') echo 'selected'; ?>>Green</option>
    </select>
    <input type="submit" value="Submit">
</form>