Using Checkboxes

You can use the POST method to send arrays of data to a script. This script adapts the previous one to allow multiple selections to be made using the checkbox form element.

<h1>Processing Checkboxes</h1>
if (isset($_POST['subject']))
   $theychose = $_POST['subject'];
   echo "<p>You chose</p><ul>";
   foreach($theychose as $itm)
      echo "<li>".$itm."</li>";

   echo "</ul>";
   echo "<form action='check.php' method='POST'>
   <p>Select some of the following items.</p>
   <p><input type='checkbox' name='subject[]' value='Geography'>Geography<br>
   <input type='checkbox' name='subject[]' value='Computing' checked='CHECKED'>Computing<br>
   <input type='checkbox' name='subject[]' value='Mathematics'>Mathematics<br>
   <input type='checkbox' name='subject[]' value='Physics'>Physics</p>

   <input type='submit' value='Submit The Form'>

Key parts of the script have been emboldened. In the else clause, you can see how the checkboxes are produced. Notice the way they are named. The square brackets contain the key or index for items in arrays. All items with this name will form part of the same array passed through the POST method.

Towards the start of the PHP, where the POST data is actually being handled, a foreach loop is being used to process the items in the array. One thing here, $itm acts a bit like a ByVal parameter in a procedure. It provides access to the value being stored but not the original variable. If you change the foreach to read foreach($theychose as &$itm), then changing the value of $itm would change the value being stored in the original array. The ampersand indicates that $itm is a reference to the variable rather than just its value.