How to Post Array From a Form in PHP

Subodh Poudel Feb 02, 2024
How to Post Array From a Form in PHP

This tutorial shows how to use the POST method to send an array from an HTML form in PHP.

Use the POST Method to Send an Array From a Form in PHP

We use the POST method to send data from a form in PHP.

The POST method is an HTTP request method that creates or adds resources to the server. We use it when we have to send sensitive information like passwords.

We need to specify the method attribute as post in the form to send a POST request. The action attribute in the form is where the request is sent. Then, we can use the $_POST superglobal variable to access the data.

We can send the data easily with the POST method in a form. For example, we can use the value of the name attribute in the $_POST array to access the data. The example is shown below.

<form action="action.php" method="post">
 <input type="input" name ="name"> <br>
 <input type="submit" value="Submit">
</form>
$name = $_POST['name']; 
echo $name"<br/>";

But, if we have to send an array of data from the form, we should add the [] sign after the value of the name attribute.

For example, we will need to send an array of data from a form while working with checkboxes. In such conditions, we can use the same value for the name attribute in all checkbox options and add the [] after the value.

For example, we need to create a form where users can select multiple checkboxes. Here, we should ensure that all the checked items are sent to the server.

First, create a form with the action attribute set to action.php. Next, set the method attribute to post, and create a checkbox for Coke using the input tag with the name colddrinks[].

Similarly, create two other checkboxes for Fanta and Sprite. Use the same colddrinks[] for the name attribute in both checkboxes.

Next, create a PHP file named action.php. Create a $coldDrinks variable and store $_POST['colddrinks'] in it.

Make sure not to omit the array symbol after colddrinks. Then, use the foreach loop to display each selected item.

The example below will display the selected name of the cold drinks. In this way, we can use the POST method to send an array from the form in PHP.

<form action="action.php" method="post">
 <input type="checkbox" name ="colddrinks[]" value="Coke"> Coke <br>
 <input type="checkbox" name ="colddrinks[]" value="Fanta"> Fanta <br>
 <input type="checkbox" name ="colddrinks[]" value="Sprite"> Sprite <br>
 <input type="submit" value="Submit">
</form>
$coldDrinks = $_POST['colddrinks']; 
foreach ($coldDrinks as $coldDrink){
 echo $coldDrink."<br/>";
}

Output:

Coke
Fanta
Subodh Poudel avatar Subodh Poudel avatar

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

LinkedIn

Related Article - PHP Array