views:

374

answers:

3
+2  Q: 

HTML input arrays

<input name="foo[]" ... >

I've used these before, but I'm wondering what it is called and if there is a specification for it?

I couldn't find it in the HTML 4.01 Spec and results in various Google results only call it an "array" along with many PHP examples of processing the form data.

+2  A: 

As far as I know, there isn't anything on the HTML specs because browsers aren't supposed to do anything different for these fields. They just send them as they normally do and PHP is the one that does the parsing into an array, as do other languages.

Paolo Bergantino
A: 

I've never seen such thing before, and I am 99.9999% sure that this isn't HTML, I think if you give more information about your problem this will really help to give you an answer

bashmohandes
It's not a problem. It's mostly curiosity...
Gerald Kaszuba
+2  A: 

I think it's just PHP, not HTML.

It parses all HTML fields with [] into an array.

So you can have

<input type="checkbox" name="food[]" value="apple" />
<input type="checkbox" name="food[]" value="pear" />
<input type="checkbox" name="food[]" value="banana" />

and when submitted, PHP will make $_POST['food'] an array, and you can access its elements like so:

echo $_POST['food'][0]; // would output first checkbox selected

or to see all values selected:

foreach( $_POST['food'] as $v ) {
    print $v;
}

Anyhow, don't think there is a specific name for it

lyrae
I think he understands this, he just wants to know if there's a spec for it.
Paolo Bergantino
As Paolo says, I do understand it! It is also used in other languages.
Gerald Kaszuba
PHP is the only language that I've encountered where the default form processing library requires special naming conventions for situations where you have more than one successful control with the same name. Other languages generally leave the determination to treat something as an array or not to the program author.
David Dorward
The "spec", such as it is, is at http://us2.php.net/manual/en/faq.html.php#faq.html.arrays
David Dorward
Further to David's comments: most server-side frameworks are smart enough to realise that if multiple form values have the same name (e.g. if three checkboxes with the same name were checked) then those values should be converted to an array when parsed on the server. For some reason, such an obvious approach has never been implemented in PHP: it requires the [] to tell it to do the sensible thing. Even Classic ASP knew better than that :-(
NickFitz