Skip to content
PHP Logo

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

When a form with radio buttons is submitted, the selected value is lost because the form is reloaded. To retain the selected radio button value after submission, you can use PHP to check if a specific radio button is selected and add the "checked" attribute to that radio button in the HTML output.

php
<?php
$selectedValue = isset($_POST['radio_button']) ? $_POST['radio_button'] : '';

// HTML form with radio buttons
echo '<form method="post">';
echo '<input type="radio" name="radio_button" value="option1" ' . ($selectedValue == 'option1' ? 'checked' : '') . '> Option 1';
echo '<input type="radio" name="radio_button" value="option2" ' . ($selectedValue == 'option2' ? 'checked' : '') . '> Option 2';
echo '<input type="submit" value="Submit">';
echo '</form>';
?>