Php – How to get an array of data from $_POST

formshtmlPHP

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:

email1@email.com, email2@email.com, email3@email.com

Instead I only get the text from the last textbox.

Best Answer

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 email1@email.com, email2@email.com ...

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.