What are some best practices for handling multiple selections in a PHP form?

When handling multiple selections in a PHP form, it is best practice to use arrays in the form field names to capture all selected values. This allows you to easily loop through the selected values and process them accordingly in your PHP script.

<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
if(isset($_POST['submit'])){
    if(isset($_POST['colors'])){
        $selectedColors = $_POST['colors'];
        foreach($selectedColors as $color){
            echo $color . "<br>";
        }
    }
}
?>