Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dealing with HTML form input when the form has a variable number of fields

Retrieving Data

Dealing with HTML form input when the form has a variable number of fields

by  sleipnir214  Posted    (Edited  )
PHP has an undocumented feature where if a set of forms have names that read like arrays, PHP will treat that input as an array.

For example, suppose your HTML form reads as follows:

Code:
<html><body><form method=POST action=test_arrayinput.php>
	<input type=text name="foo[1]">
	<input type=text name="bar[1]"><br/>
	<input type=text name="foo[2]">
	<input type=text name="bar[2]">
	<input type=submit>
</form></body></html>

If you enter data in those fields and submit it to test_arrayinput.php, in that script $_POST will be in a state like:

Code:
Array
(
    [foo] => Array
        (
            [1] => a
            [2] => b
        )
    [bar] => Array
        (
            [1] => 1
            [2] => 2
        )
)

Notes:
1. The array subscripts specified do not have to be numerical -- you can use strings as well. In that case $_POST['foo'] would be an associative array.

2. You don't have to specify indices at all in the names of your fields -- "foo[]" will work, too. This can be useful in cases where you don't care to maintain any relationships between fields. To collect input from a set of checkboxes, for example.

3. Using array subscripted field names really messes up JavaScript. If you need to reference the values of the fields in client-side JavaScript, you will not be able to using field names -- you'll have to use the JavaScript field arrays.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top