Passing arrays by POST

suggest change

Usually, an HTML form element submitted to PHP results in a single value. For example:

<pre>
<?php print_r($_POST);?>
</pre>
<form method="post">
    <input type="hidden" name="foo" value="bar"/>
    <button type="submit">Submit</button>
</form>

This results in the following output:

Array
(
    [foo] => bar
)

However, there may be cases where you want to pass an array of values. This can be done by adding a PHP-like suffix to the name of the HTML elements:

<pre>
<?php print_r($_POST);?>
</pre>
<form method="post">
    <input type="hidden" name="foo[]" value="bar"/>
    <input type="hidden" name="foo[]" value="baz"/>
    <button type="submit">Submit</button>
</form>

This results in the following output:

Array
(
    [foo] => Array
        (
            [0] => bar
            [1] => baz
        )

)

You can also specify the array indices, as either numbers or strings:

<pre>
<?php print_r($_POST);?>
</pre>
<form method="post">
    <input type="hidden" name="foo[42]" value="bar"/>
    <input type="hidden" name="foo[foo]" value="baz"/>
    <button type="submit">Submit</button>
</form>

Which returns this output:

Array
(
    [foo] => Array
        (
            [42] => bar
            [foo] => baz
        )

)

This technique can be used to avoid post-processing loops over the $_POST array, making your code leaner and more concise.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Reading request data:
* Passing arrays by POST

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
45 Reading request data
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR