Search code examples
phparraysforeach

Loop over two arrays synchronously


my html is like this

<table>
<tr>
<td><input type="text" name="input_1[]</td>
<td><input tpye="text" name="input_2[]</td>
</tr>
<tr>
<td><input type="text" name="input_1[]</td>
<td><input tpye="text" name="input_2[]</td>
</tr>
</table>

on submit, the values get posted to the next site.

i know how to handle one array[], like this:

foreach($array as $var) {
echo $var;
}

so, my problem is, i have to build an sql-Query inside the for each, it should be like

$sql="INSERT into table (value1,value2) VALUES (input_1,input_2)"

how can this be solved, i dont think for each can handle something like this:

foreach($array1 as $var1, $array2 as $var2){ 
....

Solution

  • You can use for loop to make it happen:

    <?php
    
    $a = $_POST['input_1'];
    $b = $_POST['input_2'];
    
    for($i=0; $i<count($a); $i++) {
    
        $sql="INSERT into table (value1,value2) VALUES ('{$a[$i]}','{$b[$i]}')";
        echo $sql .'<br>';
    }