Summary: in this tutorial, you will learn how to handle a form with multiple checkboxes in PHP.
How to handle multiple checkboxes on a form #
A form may contain multiple checkboxes with the same name. When you submit the form, you’ll receive multiple values on the server under one name.
To get all the values from the checked checkboxes, you need to add the square brackets ([]) after the name of the checkboxes.
When PHP sees the square brackets ([]) in the field name, it’ll create an associative array of values where the key is the checkbox’s name and the values are the selected values.
The following example shows a form that consists of three checkboxes with the same name (colors[]) with different values "red", "green", and "blue".
<form action="index.php" method="post">
<input type="checkbox" name="colors[]" value="red" id="color_red" />
<label for="color_red">Red</label>
<input type="checkbox" name="colors[]" value="green" id="color_green" />
<label for="color_red">Green</label>
<input type="checkbox" name="colors[]" value="blue" id="color_blue" />
<label for="color_red">Blue</label>
<input type="submit" value="Submit">
</form>Code language: PHP (php)When you check three checkboxes and submit the form, the $_POST['colors'] will contain an array of three selected values:
array(3)
{
[0]=> string(3) "red"
[1]=> string(5) "green"
[2]=> string(4) "blue"
}Code language: plaintext (plaintext)If you don’t check any checkboxes and submit the form, the $_POST array won’t have the colors key. And you can use the isset() function to check if the $_POST['colors'] is set:
isset($_POST['colors'])Code language: PHP (php)Alternatively, you can use the filter_has_var() function:
filter_has_var(INPUT_POST, 'colors')Code language: PHP (php)PHP multiple checkboxes example #
We’ll create a simple app that allows users to order pizza toppings.