What are some best practices for handling form submissions with multiple checkboxes in PHP?

When handling form submissions with multiple checkboxes in PHP, it is important to properly process the submitted data to account for multiple checkboxes being selected. One common approach is to use an array in the form field name for the checkboxes, which allows you to easily loop through the selected values in PHP.

// HTML form with checkboxes
<form method="post">
    <input type="checkbox" name="fruits[]" value="apple"> Apple
    <input type="checkbox" name="fruits[]" value="banana"> Banana
    <input type="checkbox" name="fruits[]" value="orange"> Orange
    <input type="submit" name="submit" value="Submit">
</form>

// PHP code to handle form submission
if(isset($_POST['submit'])) {
    if(isset($_POST['fruits'])) {
        $selectedFruits = $_POST['fruits'];
        
        foreach($selectedFruits as $fruit) {
            echo $fruit . "<br>";
        }
    } else {
        echo "No fruits selected.";
    }
}