Page 1 of 1

Merge foreach statements?

Posted: Tue Mar 13, 2007 5:56 am
by facets
Hiya,
I have a form with 3 elements that repeat many times. The following code extracts each form element no worries.
Is there any way to merge this into one statement. All 3 will ALWAYS be present. I'm guessing I could merge the 'if' lines without an issue but how could I merge the foreach lines? Obviously I need to keep driverType1, productId1 and quantityId1 'in sync'.

Any suggestions would be greatly appreciated.

tia, Will./

Code: Select all

echo "<hr><br> Delivery Type <br>";
if (isset($_POST['driverType']) && is_array($_POST['driverType'])) {
        foreach($_POST['driverType'] as $deliveryType) {
                echo $deliveryType, "<br />\n";
        }
}

echo "<hr><br> Product ID <br>";
if (isset($_POST['productId']) && is_array($_POST['productId'])) {
        foreach($_POST['productId'] as $productId) {
                echo $productId, "<br />\n";
        }
}

echo "<hr><br> Quantity <br>";
if (isset($_POST['quantityId']) && is_array($_POST['quantityId'])) {
        foreach($_POST['quantityId'] as $quality) {
                echo $quality, "<br />\n";
        }
}

Posted: Tue Mar 13, 2007 8:11 am
by feyd
Why not name the fields differently such that they will combine automatically?

For example "foo[0][driverType]", "foo[0][productId]" ... "foo[10][quantityId]"

Posted: Tue Mar 13, 2007 3:42 pm
by facets
Thanks feyd.
My HTML is being written like the HTML example below. Similar.. to your example.

So I'm thinking I need something like..

Code: Select all

Foreach drivertype
    get productId
    get quantityId
    do php code
End
I'm unsure on how to reference the productId and quantityId once in the driverType foreach loop.

Code: Select all

<select name="driverType[1]">