What are some best practices for handling form validation involving multiple checkboxes in PHP?

When handling form validation involving multiple checkboxes in PHP, it is important to loop through each checkbox input and check if it has been selected or not. This can be done by checking if the checkbox input exists in the form data array and if it has a non-empty value. By iterating through each checkbox input, you can validate multiple checkboxes effectively.

// Assume the checkboxes are named as an array in the form, e.g. <input type="checkbox" name="colors[]">

// Validate the checkboxes
if(isset($_POST['colors']) && !empty($_POST['colors'])){
    foreach($_POST['colors'] as $color){
        // Perform validation for each selected color
        // For example, you can check if the selected color is in a predefined list of allowed colors
        if(!in_array($color, ['red', 'blue', 'green'])){
            // Invalid color selected, handle the error accordingly
            $errors[] = "Invalid color selected";
        }
    }
} else {
    // No checkboxes selected, handle the error accordingly
    $errors[] = "Please select at least one color";
}