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]" ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.