I’ve seen a lot of PHP code that handles form input in which the input field names contain square brackets. I understand that this somehow results in PHP arrays when a PHP script examines the $_POST variable.
Example HTML:
<form action='http://zzz.com' method='post'>
<input name='fruit[1]' value='apple' />
<input name='fruit[2]' value='banana' />
</form>
Example URL:
http://zzz.com?fruit[1]=apple&fruit[2]=banana
Example PHP:
assert($_POST['fruit'] === array(1=>'apple', 2=>'banana'));
My questions about this:
-
What is the mechanism behind it? At what point do these names that contain brackets get converted into arrays? Is this a feature of the HTTP protocol? Of web servers? Of the PHP language?
-
Continuing the previous question, is this a commonly used hack or a normal programming tool?
-
What are (all) the rules for using brackets in input field names?
-
Can multidimensional arrays be created this way?
This is a feature of the PHP language. In fact, the HTTP protocol does not forbid the use of multiple identical GET/POST parameters. According to the HTTP spec, the following:
Should not result in
foo == baz. These are two parameters with two different values. However, PHP will overwrite the formerfoowith the latest, resulting in$_POST['foo'] == 'baz', even if they could be parsed separately.It depends on the point of view. In the PHP world, it is completely normal, as the language does not support the specification of multiple parameters of the same name without using the brackets
[]. In the HTTP world though,foo != foo[].The same as PHP arrays, except that you don’t have to quote string keys.
Yes, you can.