Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of data from $_POST

Tags:

html

forms

php

I have a form with multiple textboxes with the same names. I want to get the data from all the textboxes in my PHP code.

Here is my code.

Email 1:<input name="email" type="text"/><br/>
Email 2:<input name="email" type="text"/><br/>
Email 3:<input name="email" type="text"/><br/>
$email = $_POST['email'];
echo $email;

I wanted to have a result like this:

[email protected], [email protected], [email protected]

Instead I only get the text from the last textbox.

like image 891
Jorge Avatar asked Jun 30 '10 11:06

Jorge


People also ask

Is $_ post an array?

The PHP built-in variable $_POST is also an array and it holds the data that we provide along with the post method.

What is $_ post [] in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

How do you post data into an array?

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"/>

How does $_ post work?

The $_POST variable collects the data from the HTML form via the POST method. When a user fills the data in a PHP form and submits the data that is sent can be collected with the _POST Method in PHP. The Post Method transfers the information via the Headers.


1 Answers

Using [] in the element name

Email 1:<input name="email[]" type="text"><br>
Email 2:<input name="email[]" type="text"><br>
Email 3:<input name="email[]" type="text"><br>

will return an array on the PHP end:

$email = $_POST['email'];   

you can implode() that to get the result you want:

echo implode(", ", $email); // Will output [email protected], [email protected] ...

Don't forget to sanitize these values before doing anything with them, e.g. serializing the array or inserting them into a database! Just because they're in an array doesn't mean they are safe.

like image 98
Pekka Avatar answered Nov 15 '22 23:11

Pekka