How can PHP be used to retain selected radio button values in a form after submission?

To retain selected radio button values in a form after submission using PHP, you can store the selected value in a variable and then use that variable to set the 'checked' attribute in the radio button input tag. This way, the selected value will be retained even after the form is submitted.

<?php
// Initialize the variable to store the selected radio button value
$selectedValue = '';

// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve the selected radio button value
    $selectedValue = $_POST["radio_button"];
}

?>

<form method="post">
    <input type="radio" name="radio_button" value="option1" <?php if ($selectedValue == 'option1') echo 'checked'; ?>> Option 1
    <input type="radio" name="radio_button" value="option2" <?php if ($selectedValue == 'option2') echo 'checked'; ?>> Option 2
    <input type="radio" name="radio_button" value="option3" <?php if ($selectedValue == 'option3') echo 'checked'; ?>> Option 3

    <input type="submit" value="Submit">
</form>