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>";
}
?>