Welcome to a tutorial on how to post an array from an HTML form to PHP. The “standard” HTML form fields are easy enough. Just add the name attribute to the fields, submit the form, and that’s it. But what if we want to post an array instead?
To post an array from an HTML form to PHP, we simply append a pair of square brackets to the end of the name attribute of the input field. For example:
<form method="post">
<input name="favorites[]" type="text">
<input name="favorites[]" type="text">
<input type="submit" value="Go">
</form>
But how about doing this with AJAX? How about multi-dimensional arrays? How do we handle the post data in PHP? That is what we will walk through in this guide, with examples. Read on to find out!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
HTML POST ARRAY TO PHP
All right, let us now get into the various examples of posting an array to a PHP script.
VIDEO TUTORIAL
EXAMPLE 1) POST A SIMPLE ARRAY TO PHP
1A) THE HTML
<!-- JUST APPEND [] TO THE NAME -->
<form method="post" action="1b-basic.php">
<label>Favorite Colors</label>
<input type="text" name="colors[]" required value="red">
<input type="text" name="colors[]" required value="green">
<input type="text" name="colors[]" required value="blue">
<input type="submit" value="Submit">
</form>
As in the introduction, we only need to append square brackets []
behind the name
to POST arrays to the PHP script.
1B) SERVER-SIDE PHP
<?php
// (A) $_POST WILL CONTAIN ALL THE POSTED FORM DATA AS USUAL
print_r($_POST);
// (B) BUT $_POST["COLORS"] WILL BE AN ARRAY
foreach ($_POST["colors"] as $color) {
echo "$color<br>";
}
Yep, this should be straightforward enough. Since we defined colors[]
, $_POST["colors"]
will be an array.
EXAMPLE 2) POST NESTED ARRAY TO PHP
2A) THE HTML
<!-- USE NAME[KEY][] TO SPECIFY MULTI-DIMENSION ARRAYS -->
<form method="post" action="2b-nested.php">
<label>Favorite Colors</label>
<input type="text" name="fav[color][]" required value="red">
<input type="text" name="fav[color][]" required value="green">
<input type="text" name="fav[color][]" required value="blue">
<label>Favorite Food</label>
<input type="text" name="fav[food][]" required value="bacon">
<input type="text" name="fav[food][]" required value="eggs">
<input type="submit" value="Submit">
</form>
Multi-dimensional array fields are not that difficult either – Just use 2 square brackets, and give the first one a key. That’s it, done.
2B) SERVER-SIDE PHP
<?php
// (A) $_POST["fav"] IS A MULTI-DIMENSIONAL ARRAY
print_r($_POST["fav"]);
// (B) FAVORITE COLORS
print_r($_POST["fav"]["color"]);
// (C) FAVORITE FOOD
print_r($_POST["fav"]["food"]);
No mystery here either – $_POST["fav"]
is a multi-dimensional array as expected.
EXAMPLE 3) POSTING ARRAY WITH AJAX
3A) THE HTML
<form id="myForm" method="post" onsubmit="return save()">
<label>Favorite Colors</label>
<input type="text" name="fav[color][]" required value="red">
<input type="text" name="fav[color][]" required value="green">
<input type="text" name="fav[color][]" required value="blue">
<label>Favorite Food</label>
<input type="text" name="fav[food][]" required value="bacon>
<input type="text" name="fav[food][]" required value="eggs">
<input type="submit" value="Submit">
</form>
Not much of a difference here – Still the same HTML form, but using onsubmit="return save()"
to use Javascript AJAX to handle the submission instead.
3B) THE JAVASCRIPT
function save () {
// (A) GET FORM DATA
var form = document.getElementById("myForm"),
data = new FormData(form);
// (B) TO MANUALLY APPEND MORE DATA
data.append("address[]", "Foo Street 123");
data.append("address[]", "Hello World #234");
// (C) AJAX FETCH
fetch("3c-AJAX.php", { method:"POST", body:data })
.then(res => res.text())
.then(res => {
console.log(res);
// DO SOMETHING
});
return false;
}
Yep, simple as “ABC”.
- Collect data from the HTML form.
- Optional, we can manually append more fields to the data.
- Lastly, send the data to the server, and read the server response as text.
3C) SERVER PHP
<?php
print_r($_POST);
Nothing to see here… Just a dummy script that will echo whatever is being submitted.
EXTRAS
That’s all for this project, and here is a small section on some extras that may be useful to you.
ONLY FOR PHP!
Before the toxic trolls get angry – Take note that the above method of name="something[]"
works for PHP, but it can be different for other languages. For example, some languages may require all the name
attribute to be the same instead:
<input type="text" name="color" value="Red">
<input type="text" name="color" value="Green">
<input type="text" name="color" value="Blue">
JSON ENCODE-DECODE
To better support cross-platform data exchange, the common industry practice is to turn the array into a flat string, using JSON encode:
<script>
// (A) ARRAY TO STRING
var colors = ["Red", "Green", "Blue"];
colors = JSON.stringify(colors);
console.log(colors); // ["Red","Green","Blue"]
// (B) APPEND DATA
var data = new FormData();
data.append("colors", colors);
// (C) SEND!
fetch("4b-JSON.php", { method:"POST", body:data })
.then(res => res.text())
.then(txt => console.log(txt));
</script>
On the server side, we can do a JSON decode to get the array back.
<?php
$colors = json_decode($_POST["colors"]);
print_r($colors);
P.S. Any programming language can encode-decode a JSON string so long as there is a library or parser.
LINKS & REFERENCES
- PHP POST
- PHP GET
- Sending form data – MDN
- Form Data – MDN
- Working with JSON – MDN
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!