Why do I use brackets in the name attribute of input element?
As far as HTML is concerned, they are just characters you can use in the name, no different from a
, 7
or !
.
If you plan to access form elements via the name on the client side, then they prevent you using dot notation to do so in JavaScript (since [
has special meaning in JS) so you have to use square bracket notation instead.
You might treat the characters as having special significance once they reach the server. PHP which will file the data as $_REQUEST['user']['email']
instead of $_REQUEST['user[email]']
, and a number of other form parsing libraries for various languages have adopted the feature.
They have no particular meaning in HTML. Some server-side frameworks, including PHP, use that sort of notation as an indication that they should build up the data in a single server-side object (an associative array in PHP's case). So with PHP, for instance, if you had name="user[email]"
and name="user[phone]"
and submitted the form, in your PHP code on the server you'd retrieve a single user
object from the request and it would have the keys email
and phone
on it. Or if you had name="tags[]"
on multiple inputs, PHP would build an array with all of the values called tags
on the request object.