Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square brackets in HTML form arrays. Just conventional or with a meaning?

Tags:

arrays

html

forms

I frequently see, in particular in the PHP world, the following writing if you want to create a FORM array.

<input name="MyArray[]" />
<input name="MyArray[]" />

with the square brackets []. Nevertheless, the submit operation just passes the same key entry twice. It appears that the [] is just conventional that maps nicely to the PHP world array, but you would obtain the same result with just the following

<input name="MyArray" />
<input name="MyArray" />

Indeed, in django I get a list of two entries, regardless of the style used.

Is this true ? Are the [] just conventional, or there's actually a real meaning into it from the HTML and HTTP key/value info ?

like image 926
Stefano Borini Avatar asked Nov 06 '09 16:11

Stefano Borini


2 Answers

They address a limitation of PHP, which doesn't generate an array automatically if multiple values with the same name are submitted, for example from a set of checkboxes or a multiple select. (IIRC it only returns the last value.)

Personally I've always thought it to be a pretty shoddy workaround. Even Classic ASP could cope with that without requiring client-side additions to markup. The server-side platform has no business imposing markup requirements on the client in this way.

like image 81
NickFitz Avatar answered Oct 31 '22 09:10

NickFitz


It's just conventional.


The W3C states:

Let the form data set be a list of name-value-type tuples

and for each input element, on submit:

Append an entry to the form data set with name as the name, the value of the field element as the value, and type as the type.

The W3C does not mention the use of [] or uniqueness of the name attribute.

like image 3
jomo Avatar answered Oct 31 '22 09:10

jomo