How can PHP be used to maintain the state of checkboxes and radio buttons on a webpage?

When a webpage contains checkboxes and radio buttons, PHP can be used to maintain their states by checking the submitted form data and setting the 'checked' attribute accordingly. This can be done by using PHP to check if the checkbox or radio button value matches the submitted data, and then adding the 'checked' attribute to the HTML element if it does.

<input type="checkbox" name="example_checkbox" <?php if(isset($_POST['example_checkbox']) && $_POST['example_checkbox'] == 'on') echo 'checked'; ?>>
<input type="radio" name="example_radio" value="option1" <?php if(isset($_POST['example_radio']) && $_POST['example_radio'] == 'option1') echo 'checked'; ?>>
<input type="radio" name="example_radio" value="option2" <?php if(isset($_POST['example_radio']) && $_POST['example_radio'] == 'option2') echo 'checked'; ?>>