How to get form input array into PHP array

thom picture thom · Jul 23, 2010 · Viewed 374.3k times · Source

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

thank you for any help or advice

Answer

Jeffrey Blake picture Jeffrey Blake · Jul 23, 2010

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";
}