How to get data from an array of check boxes

The HTML that stores three related check boxes in an array

      
      <input type="checkbox" id="pep" name="top[]" checked />Pepperoni<br />
      <input type="checkbox" id="msh" name="top[]" checked />Mushrooms<br />
      <input type="checkbox" id="olv" name="top[]" checked />Olives<br />
      

PHP that accesses the array and its values

      <php
      $toppings = filter_input(INPUT_POST, 'top', 
                               FILTER_SANITIZE_SPECIAL_CHARS, FILTER_REQUIRE_ARRAY);
      if ($toppings !== NULL) { 
        $top1 = $toppings[0]; // $top1 is pep
        $top2 = $toppings[1]; // $top2 is olv
        $top3 = $toppings[2]; // $top3 is not set – throws an error
      }
      ?>
      

PHP that uses a loop to process the array

      
      <php
      $toppings = filter_input(INPUT_POST, 'top', 
                               FILTER_SANITIZE_SPECIAL_CHARS, FILTER_REQUIRE_ARRAY);
      if ($toppings !== NULL) { 
        echo("<p>");
        foreach($toppings as $key => $value) {
          echo("$key = $value<br />\n");
        }
        echo("</p>\n");
      } else {
        echo("No toppings selected.</p>\n");
      }
      ?>
      

Back