How to Post Array From HTML Form To PHP

INTRODUCTION

EASY PEASY

Welcome to a tutorial on how to post an array in HTML form, and handle the data in PHP. Handling data in an HTML form is easy. Just add the name attribute to the input field or text box and that’s it. But what if we want to post an array instead?

Long story short – 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, <input name=”favorites[]” type=”text”>.

But how about doing this in Javascript? 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.

 

 

 

PREAMBLE

DOWNLOAD & NOTES

First, here is the download link to the example source 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

There is nothing to install, so just download and unzip into a folder. 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.

 

SECTION A

THE BASICS – QUICK RECAP

Let us start with something that is easier for digestion – A quick recap on HTML forms for the beginners, and feel free to skip this section if you are already a code ninja.

 

THE HTML

1-form.html
<form method="post" action="1b-server.php">
  <label>Name</label>
  <input type="text" name="user-name" required value="John Doe"/>

  <label>Email</label>
  <input type="email" name="user-email" required value="john@doe.com"/>

  <input type="submit" value="Submit"/>
</form>
  • Captain Obvious to the rescue! To create a form in HTML, we use the <form> tag.
  • The <form> submission method can either be post or get.
    • get will append the form data to the URL as a query string. E.g. http://mysite.com/submit.php?name=John+Doe
    • post is “silent” and will not append the data to the query string.
  • The action attribute of the <form> defines which server-side script to submit the form to.
  • We sandwich <input> fields inside the <form> to collect user data input.
  • We give the <input> fields a name attribute, which will become the key in the $_POST superglobal variable. For example, when we submit  <input name="user-email">, we can get the value in PHP with $_POST['user-email'].

 

SERVER-SIDE PHP

1b-server.php
<?php
// The $_POST superglobal variable will contain all the form data
// Just dump it if you need to debug and see what is being submitted
print_r($_POST);
echo "<br><br>";

// $_POST is an array. 
// We can easily retrieve the submitted form data with:
// $_POST['user-name'] contains the name
echo "USER NAME: " . $_POST['user-name'] . "<br>";
// $_POST['user-email'] contains the email
echo "USER EMAIL: " . $_POST['user-email'] . "<br>";

 

 

SECTION B

POST AN ARRAY FROM HTML FORM

Now that we are done with the HTML form basics, let us move on to the million-dollar question – How to send an array with HTML form.

 

THE HTML

2a-form.html
<form method="post" action="2b-server.php">
  <label>Name</label>
  <input type="text" name="user-name" required value="John Doe"/>
 
  <label>Email</label>
  <input type="email" name="user-email" required value="john@doe.com"/>
 
  <!-- To send as an array, use square brackets in the name -->
  <label>Favorite Colors</label>
  <input type="text" name="user-color[]" required value="red"/>
  <input type="text" name="user-color[]" required value="green"/>
  <input type="text" name="user-color[]"/>
 
  <input type="submit" value="Submit"/>
</form>

Yep, it’s not that difficult at all.

  • To send an array, we simply append a pair of square brackets to the end of the name attribute. For example, <input type="text" name="user-color[]">.
  • Add as many <input> fields with the same name as required. In the above example, we can capture up to 3 favorite colors.
  • Please do take note of how the required attribute can only be added to 2 fields in the above example – The user is required to input at least two favorite colors, and the third is optional.

 

SERVER-SIDE PHP

2b-server.php
<?php
// For debugging - Dump if you want to see what is being submitted
print_r($_POST);
echo "<br><br>";

// You know this part...
echo "USER NAME: " . $_POST['user-name'] . "<br>";
echo "USER EMAIL: " . $_POST['user-email'] . "<br>";

// This can be a little confusing for beginners.
// $_POST is an array. $_POST['user-color'] is now an array within $_POST.
echo "FAV COLORS: <br>";
foreach ($_POST['user-color'] as $color) {
  echo $color . "<br>";
}

 

 

SECTION C

POSTING MULTI-DIMENSIONAL ARRAY

So what if we want to send a multi-dimensional array? Let us move on to the next stage.

 

THE HTML

3-form.html
<form method="post" action="3b-server.php">
  <label>Name</label>
  <input type="text" name="user-name" required value="John Doe"/>

  <label>Email</label>
  <input type="email" name="user-email" required value="john@doe.com"/>

  <!-- We can define multi-dimensional form fields similar to arrays in PHP -->
  <!-- Use 2 square brackets, give the first one a key for better organization -->
  <label>Favorite Colors</label>
  <input type="text" name="user-fav[color][]" required value="red"/>
  <input type="text" name="user-fav[color][]" required value="green"/>
  <input type="text" name="user-fav[color][]"/>

  <label>Favorite Food</label>
  <input type="text" name="user-fav[food][]" required value="bacon"/>
  <input type="text" name="user-fav[food][]" required value="eggs"/>
  <input type="text" name="user-fav[food][]" value=""/>

  <input type="submit" value="Submit"/>
</form>

Multi-dimensional form fields are not that difficult either – Just use 2 square brackets, give the first one a key. That’s it, done.

 

SERVER-SIDE PHP

3b-server.php
<?php
// For debugging - Dump if you want to see what is being submitted
print_r($_POST);
echo "<br><br>";

// You know this part...
echo "USER NAME: " . $_POST['user-name'] . "<br>";
echo "USER EMAIL: " . $_POST['user-email'] . "<br>";

// This can be a little more confusing for beginners.
// $_POST['user-fav'] is now an array of array
echo "FAV COLORS: <br>";
foreach ($_POST['user-fav']['color'] as $color) {
  echo $color . "<br>";
}

echo "FAV FOOD: <br>";
foreach ($_POST['user-fav']['food'] as $food) {
  echo $food . "<br>";
}

 

 

SECTION D

AJAX TO SEND AN ARRAY

Finally, we shall walk through how to post an array via Javascript AJAX calls.

 

THE HTML

4a-form.html
<form onsubmit="return save()">
  <label>Name</label>
  <input type="text" name="user-name" required value="John Doe"/>
 
  <label>Email</label>
  <input type="email" name="user-email" required value="john@doe.com"/>
 
  <label>Address</label>
  <input type="text" name="user-addr[]" required value="Foo Street 123"/>
  <input type="text" name="user-addr[]" required value="Hello World 345"/>
 
  <label>Favorite Colors</label>
  <input type="text" name="user-fav[color][]" required value="red"/>
  <input type="text" name="user-fav[color][]" required value="green"/>
  <input type="text" name="user-fav[color][]"/>
 
  <label>Favorite Food</label>
  <input type="text" name="user-fav[food][]" required value="bacon"/>
  <input type="text" name="user-fav[food][]" required value="eggs"/>
  <input type="text" name="user-fav[food][]" value=""/>
 
  <input type="submit" value="Submit"/>
</form>

Not much of a difference here – Still the same HTML form, but using a onsubmit="return save" to let Javascript handle the submission instead.

 

THE JAVASCRIPT

4b-form.js
function save () {
  // (A) COLLECT FORM DATA
  var data = new FormData();

  //  These should be pretty straight forward
  data.append('user-name', document.getElementsByName("user-name")[0].value);
  data.append('user-email', document.getElementsByName("user-email")[0].value);

  // We do pretty much the same in Javascript for array fields
  // Add a pair of square brackets to the end of the name
  var fields = document.getElementsByName("user-addr[]");
  for (var f of fields) {
    data.append('user-addr[]', f.value);
  }

  // Same for multi-dimensional arrays as well
  fields = document.getElementsByName("user-fav[color][]");
  for (var f of fields) {
    data.append('user-fav[color][]', f.value);
  }
  fields = document.getElementsByName("user-fav[food][]");
  for (var f of fields) {
    data.append('user-fav[food][]', f.value);
  }

  // (B) AJAX CALL
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "4c-server.php", true);

  // When the process is complete
  xhr.onload = function(){
    console.log("Done");
    console.log(this.response);
    alert("OK - See console for server response");
  };

  // Send
  xhr.send(data);
  return false;
}

This one may seem to be a little confusing to the beginners at first, but take a closer look – There are only 2 parts to this script:

  • In the first part, we are simply collecting the form data.
  • Then, send it to the server with an AJAX call.

 

SERVER PHP

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

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

 

 

EXTRA

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.

 

LINKS & REFERENCES

 

EXTRA

VIDEO TUTORIAL

For you guys who want more, here’s the video tutorial, and shameless self-promotion – Subscribe to the Code Boxx YouTube channel for more!

 

YOUTUBE TUTORIAL

 

INFOGRAPHICS CHEAT SHEET

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

 

CLOSING

WHAT’S NEXT?

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 *