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>
Related Questions
- What are the advantages and disadvantages of using a framework like ZendFramework for a larger PHP project?
- What best practices should be followed when handling password expiration and authentication in PHP applications?
- How can PHP developers optimize their code to minimize the impact of parallel processes on server performance?