Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using square brackets in hidden HTML input fields

Tags:

html

php

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?

like image 706
Ariod Avatar asked Jul 16 '09 13:07

Ariod


3 Answers

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

like image 66
Ryan Christensen Avatar answered Oct 24 '22 21:10

Ryan Christensen


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.

like image 22
Matthew Groves Avatar answered Oct 24 '22 19:10

Matthew Groves


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

like image 39
Gumbo Avatar answered Oct 24 '22 21:10

Gumbo