PHP: Multi-Checkbox

This entry is part 47 of 54 in the series PHP Tutorial

Most of the time, we work with form with multiple number of checkboxes.

Consider the code below:

<form action="multi_checkbox.php" method="post">
    Which sports do you like?<br>
    <input type="checkbox" name="sport[]" value="tennis"/>Tennis<br>
    <input type="checkbox" name="sport[]" value="swimming"/>Swimming<br>
    <input type="checkbox" name="sport[]" value="basketball"/>Basketball<br><br>

    <input type="submit" name="submit_name" value="Click Me"/>

if (isset($_POST['sport'])) {
    $array_sport = $_POST['sport'];
    $chkboxlength = count($array_sport);

    echo "You like:<br>";
    for ($i = 0; $i < $chkboxlength; $i++) {
        echo "$array_sport[$i]";
        echo "<br>";

You can try the code above here.

Notice that though I have started echoing out the array from $i=0 in line 16. Only checked boxes were printed out.

We have name=”sport[]” thus turning sport into an array declaration.  The final variable $array_sport will thus be an array.

When a box is checked, it will be inserted into the $array_sport array in line 17 starting with index=0.

Series Navigation<< PHP: Is the checkbox checked?
PHP: Print_r & var_dump >>

Leave a comment

Leave a Reply