20

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.

3 Answers 3

48

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.

Sign up to request clarification or add additional context in comments.

Comments

10
<input name="email[]" type="text">
<input name="email[]" type="text">
<input name="email[]" type="text">
<input name="email[]" type="text">

$_POST['email'] will be an array.

Comments

5

Another example could be:

<input type="text" name="email[]" value="1">
<input type="text" name="email[]" value="2">
<input type="text" name="email[]" value="3">

<?php
     foreach($_REQUEST['email'] as $key => $value)
          echo "key $key is $value <br>";

will display

key 0 is 1
key 1 is 2
key 2 is 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.