0

I have a HTML form with field names like field11, field12, field13 in the first row and field21, field22, field23 in the second row and so on. I have this dynamic naming structure, because the user sets the number of rows and columns. I use two nested PHP for loops to build this table. Everything works fine until I submit the form and wish to retrieve the values on the next page. To retrieve field21, I need to use $_POST["field21"]. But I am using this inside a double for loop where $i=2 and $j=1. In essence, I need to use something like $_POST["field . $i . $j"]. I am not able to get the correct syntax.

for ($j = 1; $j <= $sailings; $j++) {
for ($i = 1; $i < $ratecols; $i++) {

echo "<td><input name='field" . $j . $i . "' id='field" . $j . $i . "' type='text'></td>";

}
}
1
  • What is your problem? reading the values after form submission not knowing how many rows and columns exist? Commented Aug 29, 2019 at 12:59

3 Answers 3

3

Instead - use [] notation for name attribute of your inputs:

<input name="field[1][1]" type='text' />
<input name="field[1][2]" type='text' />
<input name="field[1][3]" type='text' />
<input name="field[2][1]" type='text' />
<input name="field[2][2]" type='text' />
<input name="field[2][3]" type='text' />

On server iterate over $_POST['field']:

foreach ($_POST['field'] as $row) {
    foreach ($row as $value) {
        echo $value; 
        // other code
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to read the field values the way you are outputting them you can do it like this:

for ($j = 1; isset($_POST['field' . $j . 1]); $j++) {
    for ($i = 1; isset($_POST['field' . $j . $i]); $i++) {
        echo $_POST['field' . $j . $i];
    }
}

Although I suggest you use the approach posted by u_mulder since it is the correct one.

Comments

0

Just use a key value foreach loop:

<?php

$_POST = [
  'var1' => 'www',
  'var2' => 'xxx',
  'var3' => 'yyy',
  'var4' => 'zzz',  
];

foreach ($_POST as $key => $value) {
    echo 'Form field ' . $key . ' = ' . $value . "\n";
}

Which will output:

Form field var1 = www 
Form field var2 = xxx 
Form field var3 = yyy 
Form field var4 = zzz

Which you can see here https://3v4l.org/FKlY8

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.