Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

Passing Arrays in Forms


Though it may not be apparent, it is possible to pass arrays from a form. To understand
how, you must recall how form fields are turned into PHP variables. Each field is read in
order by PHP and turned into an assignment statement. A URL like
http://www.somesite.com/script.php3?name=leon creates an assignment
like $name = "leon", which means that before the script begins executing, the name
variable is set.


The name of the form field is treated as the left side of an assignment statement. This
means that if other special characters appear as part of the name of the field, they will
interpreted accordingly. You can include square brackets to force the variable to be an
array. An empty pair of square brackets will add a value to an array using consecutive
integers. So, if you name multiple fields in a form with the same name that ends in a pair
of empty brackets, an array will be constructed for you when the form is submitted.
Listing 20.12 illustrates this method.


There are limitations to this technique. Only single-dimension arrays are passed correctly.
You also need to be aware of buggy browsers. You should always place double quotes
around field names anyway, but I've run into browsers that don't pass fields properly
when fields ending in square brackets aren't quoted.


Listing 20.12 Passing an Array via a Form

Free download pdf