Using square brackets in hidden HTML input fields

I am analyzing someone else's PHP code and I've noticed that the input HTML has many hidden input fields with names that end with '[]', for instance:

<input type="hidden" name="ORDER_VALUE[]" value="34" />
<input type="hidden" name="ORDER_VALUE[]" value="17" />

The PHP page that processes this input acquires each value like this:

foreach ($_REQUEST["ORDER_VALUE"] as $order_value) {
    /...
}

What is the '[]' used for? Specifying that there would be multiple input fields with the same name?


Solution 1:

It passes data as an array to PHP. When you have HTML forms with the same name it will append into comma lists like checkbox lists. Here PHP has processing to convert that to a PHP array based on the [] like so:

To get your result sent as an array to your PHP script you name the , or elements like this:

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

Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:

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

This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays:

<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />

http://us2.php.net/manual/en/faq.html.php

Solution 2:

Yes. Basically PHP will know to stick all of those values with the same name into an array.

This applies to all input fields, by the way, not just hidden ones.

Solution 3:

See How do I create arrays in a HTML <form>? in the PHP FAQ.