Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

9.10. Using Form Elements with Multiple Options

Problem

You have a form element with multiple values, such as a checkbox or select element, but PHP sees only one value.

Solution

Place brackets ([ ]) after the variable name:

<input type="checkbox" name="boroughs[]" value="bronx"> The Bronx
<input type="checkbox" name="boroughs[]" value="brooklyn"> Brooklyn
<input type="checkbox" name="boroughs[]" value="manhattan"> Manhattan
<input type="checkbox" name="boroughs[]" value="queens"> Queens
<input type="checkbox" name="boroughs[]" value="statenisland"> Staten Island

Inside your program, treat the variable as an array:

print 'I love ' . join(' and ', $boroughs) . '!';

Discussion

By placing [ ] after the variable name, you tell PHP to treat it as an array instead of a scalar. When it sees another value assigned to that variable, PHP auto-expands the size of the array and places the new value at the end. If the first three boxes in the Solution were checked, it’s as if you’d written this code at the top of the script:

$boroughs[ ] = "bronx";
$boroughs[ ] = "brooklyn";
$boroughs[ ] = "manhattan";

You can use this to return information from a database that matches multiple records:

foreach ($_GET['boroughs'] as $b) {
  $boroughs[ ] = strtr($dbh->quote($b),array('_' => '\_', '%' => '\%'));
}
$locations = join(',', $boroughs);

$dbh->query("SELECT address FROM locations WHERE borough IN ($locations)");

This syntax also works with multidimensional arrays:

<input type="checkbox" name="population[NY][NYC]" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata