How can PHP be used to preselect a radio button based on a previous user selection in a form?
When a user makes a selection in a form with radio buttons, PHP can be used to preselect the radio button based on the user's previous selection. This can be achieved by storing the user's selection in a session variable and then checking that variable to determine which radio button should be preselected when the form is loaded again.
<?php
session_start();
// Check if user has made a selection
if(isset($_POST['radio_option'])) {
$_SESSION['selected_option'] = $_POST['radio_option'];
}
// Define radio button options
$options = ['Option 1', 'Option 2', 'Option 3'];
// Display radio buttons with preselected option
foreach($options as $option) {
$checked = ($_SESSION['selected_option'] == $option) ? 'checked' : '';
echo "<input type='radio' name='radio_option' value='$option' $checked>$option<br>";
}
?>
Keywords
Related Questions
- What are the best practices for handling file transfers between servers using PHP?
- How can PHP scripts interact with server-side programs like htpasswd to manage access control for directories on a website?
- What best practices should be followed when joining tables in PHP to avoid missing data in the results?