What are some common pitfalls when dealing with multiple checkbox selections in PHP forms?

One common pitfall when dealing with multiple checkbox selections in PHP forms is not properly handling the array of selected values. To solve this, make sure to use square brackets in the input name attribute to create an array of values. Another pitfall is not checking if a checkbox is checked before accessing its value, which can lead to errors if the checkbox is not selected.

// Example form with multiple checkboxes
<form method="post">
    <input type="checkbox" name="colors[]" value="red"> Red
    <input type="checkbox" name="colors[]" value="blue"> Blue
    <input type="checkbox" name="colors[]" value="green"> Green
    <input type="submit" name="submit" value="Submit">
</form>

<?php
// Check if form is submitted
if(isset($_POST['submit'])) {
    // Check if colors array is set
    if(isset($_POST['colors'])) {
        // Loop through selected colors
        foreach($_POST['colors'] as $color) {
            echo $color . "<br>";
        }
    }
}
?>