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.

 

 

REAL QUICK TUTORIAL

 

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.

 

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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

HOW TO POST ARRAYS

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

 

1) POST SIMPLE ARRAY TO PHP

THE HTML

1a-basic.html
<form method="post" action="1b-server.php">
  <label>Favorite Colors</label>
  <!-- JUST APPEND [] BEHIND THE NAME -->
  <input type="text" name="colors[]" required value="red"/>
  <input type="text" name="colors[]" required value="green"/>
  <input type="text" name="colors[]"/>
  <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.

 

 

2) POST NESTED ARRAY TO PHP

THE HTML

2a-nested.html
<form method="post" action="2b-server.php">
  <!-- JUST AS IN PHP, WE USE NAME[KEY][] TO SPECIFY MULTI-DIMENSION ARRAYS -->
  <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][]"/>
 
  <label>Favorite Food</label>
  <input type="text" name="fav[food][]" required value="bacon"/>
  <input type="text" name="fav[food][]" required value="eggs"/>
  <input type="text" name="fav[food][]"/>
 
  <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'] ITSELF WILL BE 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'] will become a multi-dimensional array as expected.

 

 

3) POSTING ARRAY WITH AJAX

THE HTML

3a-AJAX.html
<form method="post" onsubmit="return save()">
  <label>Address</label>
  <input type="text" name="addr[]" required value="Foo Street 123"/>
  <input type="text" name="addr[]" required value="Hello World 345"/>
 
  <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][]"/>
 
  <label>Favorite Food</label>
  <input type="text" name="fav[food][]" required value="bacon"/>
  <input type="text" name="fav[food][]" required value="eggs"/>
  <input type="text" name="fav[food][]"/>
 
  <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 data = new FormData(),
      fields = null;

  // (A1) SIMPLE ARRAY
  fields = document.getElementsByName("addr[]");
  for (let f of fields) { data.append('addr[]', f.value); }

  // (A2) NESTED ARRAY
  fields = document.getElementsByName("fav[color][]");
  for (var f of fields) { data.append('fav[color][]', f.value); }
  fields = document.getElementsByName("fav[food][]");
  for (var f of fields) { data.append('fav[food][]', f.value); }

  // (B) AJAX CALL
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "3c-AJAX.php");
  xhr.onload = function(){
    console.log(this.response);
    alert("OK - See console for server response");
  };
  xhr.send(data);
  return false;
}

This may seem to be a little confusing to beginners at first, but keep calm and look closer. There are only 2 parts to this script:

  • A – Simply collect data from the HTML form fields.
  • B  – Then, send it to the server with an AJAX call.

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 extra note that the above array format 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"/>

Or alternatively, the server-side script can be made to accept a JSON encoded string.

<script>
var data = ["Red", "Green", "Blue"];
document.getElementById("color").innerHTML = JSON.stringify(data);
</script>
<input type="text" name="color" id="color"/>

Key point is, it is all up to how the server-side implementation is done.

 

YOUTUBE TUTORIAL

 

INFOGRAPHICS CHEAT SHEET

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

 

LINKS & REFERENCES

 

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. Required fields are marked *