home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomePHP CookbookSearch this book

9.11. Using Form Elements with Multiple Options

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:

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

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

Library Navigation Links

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