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
Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.
The PHP built-in variable $_POST is also an array and it holds the data that we provide along with the post method.
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"/>
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"; }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With