charlie
charlie

Reputation: 481

PHP get post data from inputs with arrays []

I am creating a form that users can add extra fields to dynamically and every time a new input is created, it is named accountemails[type] with the type being different for each group.

I want to post this form and retrieve the data grouped by the type

For example, if I have 2 groups - group1 and group2 my inputs would be named:

name="accountemails[group1]"
name="accountemails[group2]"

And there could be multiple with the same group name

For the post in php, I tried

foreach($_POST["accountemails"] as $type => $email) {

}

Which I though would work and I could use $type as each group and then $email for each value but that only shows the last posted input value per group

Upvotes: 1

Views: 146

Answers (2)

Kitson88
Kitson88

Reputation: 2940

To elaborate on Benoti's answer, it sounds like your overwriting your $_POST['accountemails'] data when a new value is added. Add the group data to an array.

$_POST['accountemails']['group1'] [] = "Group 1 - 1"; //Emulates html form: name = accountemails[group1][] with value of: Group 1 - 1
$_POST['accountemails']['group1'] [] = "Group 1 - 2"; //Emulates html form: name = accountemails[group1][] with value of: Group 1 - 2

$_POST['accountemails']['group2'] [] = "Group 2 - 1"; //Emulates html form: name = accountemails[group2][] with value of: Group 2 - 1
$_POST['accountemails']['group2'] [] = "Group 2 - 2"; //Emulates html form: name = accountemails[group2][] with value of: Group 2 - 2

foreach ($_POST as $v) {

    foreach ($v['group1'] as $email) {

        echo "Group 1 Email: " . $email;
        echo "<br>";
    }

    foreach ($v['group2'] as $email) {

        echo "Group 2 Email: " . $email;
        echo "<br>";     
    }
}

Output

Group 1 Email: Group 1 - 1
Group 1 Email: Group 1 - 2
Group 2 Email: Group 2 - 1
Group 2 Email: Group 2 - 2

Upvotes: 1

Benoti
Benoti

Reputation: 2200

If you want to add multiple form input with the same name, you need to add double brackets at the very last end of the name.

 name="accountemails[group1][]"
 name="accountemails[group2][]"

Then if the user adds extra-fields for group1, each new accountemails in each different group will be added to an array that you'll be able to retrieve in your foreach loop.

Upvotes: 1

Related Questions