MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP Passing arrays by POST


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>

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>

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>

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.

Conclusion

In this page (written and validated by ) you learned about PHP Passing arrays by POST . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Uploading files with HTTP PUT.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.