PHP Passing arrays by POST


Example

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.