How can the checked attribute be properly set in a radio input to maintain the selected values in PHP?
When a form is submitted and processed in PHP, the checked attribute needs to be properly set in radio inputs to maintain the selected values. This can be achieved by checking if the value of the radio input matches the value submitted in the form data, and then adding the checked attribute if they match. This ensures that the selected radio input remains checked after form submission.
<?php
// Assume $selectedValue contains the value submitted in the form data
$option1Checked = ($selectedValue == 'option1') ? 'checked' : '';
$option2Checked = ($selectedValue == 'option2') ? 'checked' : '';
$option3Checked = ($selectedValue == 'option3') ? 'checked' : '';
?>
<input type="radio" name="options" value="option1" <?php echo $option1Checked; ?>> Option 1
<input type="radio" name="options" value="option2" <?php echo $option2Checked; ?>> Option 2
<input type="radio" name="options" value="option3" <?php echo $option3Checked; ?>> Option 3