How can session variables be used to maintain checkbox selections in PHP forms?

When a user selects checkboxes on a form in PHP, the selections are not automatically maintained when the form is submitted. To address this, we can use session variables to store the checkbox selections and then populate the checkboxes with the stored values when the form is reloaded. This allows the user to see their previous selections and make any necessary changes before submitting the form.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store checkbox selections in session variable
    $_SESSION['checkbox_values'] = $_POST['checkbox'];
} else {
    // Initialize checkbox selections from session variable
    $checkbox_values = isset($_SESSION['checkbox_values']) ? $_SESSION['checkbox_values'] : [];
}

// Display form with checkboxes
?>

<form method="post">
    <input type="checkbox" name="checkbox[]" value="option1" <?php if (in_array('option1', $checkbox_values)) echo 'checked'; ?>> Option 1<br>
    <input type="checkbox" name="checkbox[]" value="option2" <?php if (in_array('option2', $checkbox_values)) echo 'checked'; ?>> Option 2<br>
    <input type="checkbox" name="checkbox[]" value="option3" <?php if (in_array('option3', $checkbox_values)) echo 'checked'; ?>> Option 3<br>
    
    <input type="submit" value="Submit">
</form>