How can PHP be used to retain user selections in a select box after form submission?

When a form is submitted, the selected option in a select box is not retained by default. To retain user selections in a select box after form submission, you can use PHP to check the submitted value and set the "selected" attribute for the corresponding option in the select box.

<select name="color">
    <option value="red" <?php if(isset($_POST['color']) && $_POST['color'] == 'red') echo 'selected'; ?>>Red</option>
    <option value="blue" <?php if(isset($_POST['color']) && $_POST['color'] == 'blue') echo 'selected'; ?>>Blue</option>
    <option value="green" <?php if(isset($_POST['color']) && $_POST['color'] == 'green') echo 'selected'; ?>>Green</option>
</select>