105

I have a form like the one below which is posted to contacts.php, and the user can dynamically add more with jQuery.

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

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

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

If I echo them out in PHP with the code below,

$name = $_POST['name'];
$email = $_POST['account'];

foreach($name as $v) {
    print $v;
}

foreach($email as $v) {
    print $v;
}

I will get something like this:

name1name2name3email1email2email3

How can I get those arrays into something like the code below?

function show_Names($n, $m)
{
    return("The name is $n and email is $m, thank you");
}

$a = array("name1", "name2", "name3");
$b = array("email1", "email2", "email3");

$c = array_map("show_Names", $a, $b);
print_r($c);

so my output is like this:

The name is name1 and email is email1, thank you The name is name2 and email is email2, thank you The name is name3 and email is email3, thank you

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
thom
  • 1,306
  • 4
  • 12
  • 15

9 Answers9

160

They are already in arrays: $name is an array, as is $email

So all you need to do is add a bit of processing to attack both arrays:

$name = $_POST['name'];
$email = $_POST['account'];

foreach( $name as $key => $n ) {
  print "The name is " . $n . " and email is " . $email[$key] . ", thank you\n";
}

To handle more inputs, just extend the pattern:

$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];

foreach( $name as $key => $n ) {
  print "The name is " . $n . ", email is " . $email[$key] .
        ", and location is " . $location[$key] . ". Thank you\n";
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
  • thank you, what if i added another input like location[], how could i add that in as well? – thom Jul 23 '10 at 01:06
  • 1
    Basically, you just extend the pattern. See my edit above...any additional inputs will also be arrays when you assign them from $_POST (assuming there are multiple inputs with that name in the html, as you did with these fields). – Jeffrey Blake Jul 23 '10 at 01:12
  • 1
    Jeffrey, I wonder if I can trust the ordering of the arrays. That is, are we sure that `$emails[1]` corresponds to the user named `$name[1]`? I think I ran into problems with this in the past but I might be wrong. Thanks – nicolagi Nov 13 '12 at 11:19
  • 1
    @bruciasse - The way that the server handles input arrays like this will vary from one web server to another (different OSes implement things differently when it comes to fine grained details like this), however every platform I have employed these techniques on is consistent within itself (i.e. the ordering is the same every time). It is possible that a browser could mix-up the order of the request variables before passing the request to the server, but I would expect this to be fairly unusual. The final issue you could face is that of the html being mixed in a strange order and CSS adjusting – Jeffrey Blake Nov 14 '12 at 13:11
  • ... the positioning. If your page was like that, it would certainly see some strange issues w/r/t ordering of the arrays. – Jeffrey Blake Nov 14 '12 at 13:12
  • @JeffreyBlake, there is an issue with this, `foreach` uses an array of values, doing `$name = $_POST['name'];` would leave this as a string so the system will break as soon as you try to traverse it as an array rather than a string, did you mean `$name[] = $_POST['name'];` instead of this? (Sorry it's belated, just rather misleading when I saw this...) – Can O' Spam Jul 10 '15 at 14:33
  • @SamSwift You're assuming that `$_POST['name']` is a string. In the case that your page has multiple `` elements with the same value for name, that is not the case. When that happens, PHP will load the `$_POST` variable as an array. It is true that this code might not work as desired in the case that there is only one input element. If you're doing something with a dynamically generated form that can have any number of inputs, you might have to add processing for the cases of having zero or one inputs, as opposed to many, however that is outside the scope of this question/answer. – Jeffrey Blake Jul 11 '15 at 16:13
  • how about input type file? could you help me with this ty – dadan Feb 02 '17 at 04:21
58

E.g. by naming the fields like

<input type="text" name="item[0][name]" />
<input type="text" name="item[0][email]" />

<input type="text" name="item[1][name]" />
<input type="text" name="item[1][email]" />

<input type="text" name="item[2][name]" />
<input type="text" name="item[2][email]" />

(which is also possible when adding elements via JavaScript)

The corresponding PHP script might look like

function show_Names($e)
{
  return "The name is $e[name] and email is $e[email], thank you";
}

$c = array_map("show_Names", $_POST['item']);
print_r($c);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • Hi Thanks for this, how do you do the php script in laravel function show_Names($e) { return "The name is $e[name] and email is $e[email], thank you"; } $c = array_map("show_Names", $_POST['item']); print_r($c); – Jeche Jan 05 '21 at 07:44
4

You could do something such as this:

function AddToArray ($post_information) {
    //Create the return array
    $return = array();
    //Iterate through the array passed
    foreach ($post_information as $key => $value) {
        //Append the key and value to the array, e.g.
            //$_POST['keys'] = "values" would be in the array as "keys"=>"values"
        $return[$key] = $value;
    }
    //Return the created array
    return $return;
}

The test with:

if (isset($_POST['submit'])) {
    var_dump(AddToArray($_POST));
}

This for me produced:

array (size=1)
  0 =>
    array (size=5)
      'stake' => string '0' (length=1)
      'odds' => string '' (length=0)
      'ew' => string 'false' (length=5)
      'ew_deduction' => string '' (length=0)
      'submit' => string 'Open' (length=4)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Can O' Spam
  • 2,718
  • 4
  • 19
  • 45
2

I came across this problem as well. Given 3 inputs: field[], field2[], field3[]

You can access each of these fields dynamically. Since each field will be an array, the related fields will all share the same array key. For example, given input data:

  • Bob, bob@bob.com, male
  • Mark, mark@mark.com, male

Bob and his email and sex will share the same key. With this in mind, you can access the data in a for loop like this:

    for($x = 0; $x < count($first_name); $x++ )
    {
        echo $first_name[$x];
        echo $email[$x];
        echo $sex[$x];
        echo "<br/>";
    }

This scales as well. All you need to do is add your respective array vars whenever you need new fields to be added.

thatonefreeman
  • 174
  • 1
  • 10
2

You can use an array of fieldsets:

<fieldset>
    <input type="text" name="item[1]" />
    <input type="text" name="item[2]" />
    <input type="hidden" name="fset[]"/>
</fieldset>

<fieldset>
    <input type="text" name="item[3]" />
    <input type="text" name="item[4]" />
    <input type="hidden" name="fset[]"/>
</fieldset>

I added a hidden field to count the number of the fieldsets. The user can add or delete the fields and then save it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sophia Gavish
  • 467
  • 2
  • 8
  • 16
0

However, VolkerK's solution is the best to avoid miss couple between email and username. So you have to generate HTML code with PHP like this:

<? foreach ($i = 0; $i < $total_data; $i++) : ?>
    <input type="text" name="name[<?= $i ?>]" />
    <input type="text" name="email[<?= $i ?>]" />
<? endforeach; ?>

Change $total_data to suit your needs. To show it, just like this:

$output = array_map(create_function('$name, $email', 'return "The name is $name and email is $email, thank you.";'), $_POST['name'], $_POST['email']);
echo implode('<br>', $output);

Assuming the data was sent using POST method.

iroel
  • 1,760
  • 1
  • 18
  • 27
0

This is an easy one:

foreach($_POST['field'] as $num => $val) {
    print ' ' . $num . ' -> ' . $val . ' ';
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ian
  • 74
  • 7
  • An explanation would be in order. E.g., what is the idea/gist? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/53300708/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 18 '21 at 20:51
0

Already is an array. My inputs are:

<input name="name[]" value='joe'>
<input name="lastname[]" value='doe'>
<input name="name[]" value='jose'>
<input name="lastname[]" value='morrison'>

In the $_POST data, returns the following:

[name] => Array
    (
        [0] => 'joe'
        [1] => 'jose'
    )
[lastname] => Array
    (
        [0] =>  'doe'
        [1] => 'morrison'
    )

You can access to these data, in the following way:

$names = $_POST['name']
$lastnames = $_POST['lastname']
// accessing
echo $names[0]; // joe

This way It is very useful for creating pivot tables.

-4

Using this method should work:

$name = $_POST['name'];
$email = $_POST['account'];
while($explore=each($email)) {
    echo $explore['key'];
    echo "-";
    echo $explore['value'];
    echo "<br/>";
}
Nic
  • 12,220
  • 20
  • 77
  • 105
  • Explain your answer step by step – krisdestruction Apr 23 '15 at 22:09
  • An explanation would be in order. E.g., what is the idea/gist? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/29834972/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 18 '21 at 20:46