How can PHP sessions be effectively utilized to retain checkbox selections in a form for later use?

To retain checkbox selections in a form for later use, PHP sessions can be used to store the selected values. When a checkbox is selected, its value can be stored in a session variable. When the form is submitted or reloaded, the session variable can be checked to pre-select the checkboxes that were previously selected.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store selected checkboxes in session
    $_SESSION['selected_checkboxes'] = $_POST['checkbox'];
} else {
    // Set selected checkboxes based on session data
    $selected_checkboxes = isset($_SESSION['selected_checkboxes']) ? $_SESSION['selected_checkboxes'] : [];
}

// Display checkboxes in form
$checkbox_options = ['Option 1', 'Option 2', 'Option 3'];

foreach ($checkbox_options as $option) {
    $checked = in_array($option, $selected_checkboxes) ? 'checked' : '';
    echo "<input type='checkbox' name='checkbox[]' value='$option' $checked> $option <br>";
}
?>