1

I have a form with 5 input fields. Each field has an array name, because there is possiblity of more than one record creation at once.

Example:

<input type="text" name="name[]" />
<input type="text" name="surname[]" />
<input type="text" name="address[]" />
<input type="text" name="phone[]" />
<input type="text" name="age[]" />

My question is how to manage multiple name arrays with php? I know how to do it with single array (multiple checkboxes checked case), but i got stuck here.

$all[] = $_POST["name"];
$all[] = $_POST["surname"];
$all[] = $_POST["address"];
$all[] = $_POST["phone"];
$all[] = $_POST["age"];
???

foreach {....???

3 Answers 3

3

Each input will have an index and, by multiplying all the values, all fields within same group will have same array index:

foreach($_POST['name'] as $num => $one){

    echo $_POST['name'][$num]; // or $one
    echo $_POST['surname'][$num];
    echo $_POST['address'][$num];
    echo $_POST['phone'][$num];
    echo $_POST['age'][$num];
}
Sign up to request clarification or add additional context in comments.

4 Comments

you would need to check if that index is set for other fields other than name[](surname,address etc) else you would get an undefined error, if the field isn't set.
One more question. Only first can be called with variable $one? All others should be called using $_POST, right?
@sweettea i have validation / all fields are required anyways :)
yes, only first because that is the array I started with, but you can use $num for all ..
0

You can do like this:

$all = $_POST["name"];
foreach($all as $val) {
    //Do whatever with $val
}

Comments

0

In this case it's probably best to use multidimensional arrays like so:

$all['name'] = $_POST['name'];
$all['surname'] = $_POST['surname'];
$all['address'] = $_POST['address'];
$all['phone'] = $_POST['phone'];
$all['age'] = $_POST['age'];

//1st processing option
foreach ($all as $key => $dataList) {
    //some code
    foreach ($dataList as $data) {
        //some code
    }
}

//2nd processing option
foreach ($all['name'] as $data) {
    //some code
}
//repeat for each of 'name, surname, address, phone, age'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.