What are the best practices for maintaining the selected state of checkboxes and select options after form submission in PHP?

When a form is submitted in PHP and the page reloads, the selected state of checkboxes and select options is not maintained by default. To maintain the selected state after form submission, you can use PHP to check if the value of each checkbox or select option matches the submitted value, and add the "checked" attribute for checkboxes or "selected" attribute for select options accordingly.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $selectedOption = $_POST["select_option"];
}

// Display form with selected state maintained
?>
<form method="post">
    <input type="checkbox" name="checkbox_option" value="1" <?php if(isset($_POST["checkbox_option"]) && $_POST["checkbox_option"] == "1") echo "checked"; ?>>
    <select name="select_option">
        <option value="option1" <?php if(isset($selectedOption) && $selectedOption == "option1") echo "selected"; ?>>Option 1</option>
        <option value="option2" <?php if(isset($selectedOption) && $selectedOption == "option2") echo "selected"; ?>>Option 2</option>
        <option value="option3" <?php if(isset($selectedOption) && $selectedOption == "option3") echo "selected"; ?>>Option 3</option>
    </select>
    <button type="submit">Submit</button>
</form>