How to Post Array From HTML Form To PHP (Simple Examples)

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!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes POST Array Useful Bits & Links
The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

HOW TO POST ARRAYS

All right, let us now get into the various examples of posting an array to a PHP script.

 

EXAMPLE 1) POST SIMPLE ARRAY TO PHP

THE HTML

1a-basic.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.

 

SERVER-SIDE PHP

1b-basic.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

THE HTML

2a-nested.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, give the first one a key. That’s it, done.

 

SERVER-SIDE PHP

2b-nested.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

THE HTML

3a-AJAX.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.

 

THE JAVASCRIPT

3b-form.js
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((response) => {
    console.log(response);
  });
  return false;
}

Yep, simple as “ABC”.

  1. Collect data from the HTML form.
  2. Optional, we can manually append more fields to the data.
  3. Lastly, send the data to the server, read the server response as text.

 

SERVER PHP

3c-server.php
<?php
print_r($_POST);

Nothing to see here… Just a dummy script that will echo whatever is being submitted.

 

 

USEFUL BITS & LINKS

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 adding [] to the name 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) SEND AS FLAT STRING
var data = new FormData(form);
data.append("colors", colors);
fetch("SCRIPT", { method:"POST", body:data });
</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

 

YOUTUBE TUTORIAL

 

INFOGRAPHICS CHEAT SHEET

How to Post Array with HTML Form (Click to Enlarge)

 

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!

Leave a Comment

Your email address will not be published.