Are there any best practices for maintaining user selections in radio buttons after form submission in PHP?

When a form with radio buttons is submitted in PHP, the selected value may not be maintained in the radio button after submission. To maintain the user selection, you can store the selected value in a variable and use the "checked" attribute in the radio button input tag to pre-select the value after form submission.

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

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the selected value from the form submission
    $selectedValue = $_POST['radio_button'];
}

?>

<form method="post" action="">
    <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>