[php] How to get form input array into PHP array

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

This question is related to php arrays forms

The answer is


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 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.


Nonetheless, you can use below code as,

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

function f($a,$b){
    return "The name is $a and email is $b, thank you";
}

$c = array_map('f', $a, $b);

//echoing the result

foreach ($c as $val) {
    echo $val.'<br>';
}

I know its a bit late now, but 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)

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);

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.


Using this method should work:

$name = $_POST['name'];
$email = $_POST['account'];
while($explore=each($email)) {
    echo $explore['key'];
    echo "-";
    echo $explore['value'];
    echo "<br/>";
}

What if you've got 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.


This is easy one:

foreach( $_POST['field'] as $num => $val ) {
      print ' '.$num.' -> '.$val.' ';
    }

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"