What are best practices for handling form data in PHP to ensure that selected options are maintained and displayed correctly in the form?

When handling form data in PHP, it's important to ensure that selected options are maintained and displayed correctly in the form. One way to achieve this is by using conditional statements to check if an option should be selected based on the submitted data.

<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>