start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

9.11. Using Form Elements with Multiple Options

9.11.1. Problem

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

9.11.2. 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) . '!';

9.11.3. 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]" value="8008278">New York...

If checked, this form element sets $population['NY']['NYC'] to 8008278.

Placing a [ ] after a variable's name can cause problems in JavaScript when you try to address your elements. Instead of addressing the element by its name, use the numerical ID. You can also place the element name inside single quotes. Another way is to assign the element an ID, perhaps the name without the [ ], and use that ID instead. Given:

<form>
<input type="checkbox" name="myName[]" value="myValue" id="myName">
</form>

the following three refer to the same form element:

document.forms[0].elements[0];            // using numerical IDs
document.forms[0].elements['myName[ ]'];   // using the name with quotes
document.forms[0].elements['myName'];     // using ID you assigned

9.11.4. See Also

The introduction to Chapter 4 for more on arrays.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.