Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

I know this is necro-posting, but I have been running to this same issue and ending up to this same answer many, many, many times, over some years.

Today though I had an additional issue, I wanted my users to be able to add as many items as they want, as well as rearrange their input before submitting, so I came up with this relatively clean solution:

$diameters = [];
foreach($_POST['diameters'] as $k=>$v){
 $val = intdiv($k,2);
 $diameters[$val][key($v)]=$v[key($v)];
}
$_POST['diameters']=$diameters;

The hard coded 2 is because that is the size of the input block (topdiameter, bottomdiameter)

So the html can simply look like this:

<tr>
  <td><input name="diameters[][top]" type="text" [..] /></td>
  <td><input name="diameters[][bottom]" type="text" [..] /></td>
</tr>
<tr>
  <td><input name="diameters[][top]" type="text" [..] /></td>
  <td><input name="diameters[][bottom]" type="text" [..] /></td>
</tr>

This way you will end up having a simple array in the format of:

$_POST['diameters']=[
  ["top"=>"","bottom"=>""],
  ["top"=>"","bottom"=>""],
  ...
]

Which should make whatever you need to do with your data much simpler.


On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}