Check boxes in forms (PHP)

This tutorial explains how to create a form which contains check boxes and how to handle the form data using PHP. Check boxes are used when you want the user to be able to select one or several options (unlike radio buttons which only allow the user to select one option at a time). Watch the video below and then scroll down to see the sample code.

Sample PHP code:

Step 1: Create a PHP file which will contain the form (eg. form.php) and copy the following code into it. This example will ask the user to select a country or multiple countries they would like to visit.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Which countries would you like to visit?</p>
    <input type="checkbox" value="France" name="countries[]"> France<br/>
    <input type="checkbox" value="India" name="countries[]"> India<br/>
    <input type="checkbox" value="Brazil" name="countries[]"> Brazil<br/>
    <input type="checkbox" value="Japan" name="countries[]"> Japan<br/>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate PHP file which will handle the submitted form data and call it action_handler.php – then copy the following code into the file.

<?php
  if(isset($_POST['countries'])){
    $countries = $_POST['countries'];
    echo "You selected the following countries:<br/>";
    foreach($countries as $key => $value){
      echo "$value<br/>";
    }
  }
  else{
    echo "You must select at least one country.";
  }
?>