Merge foreach statements?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
facets
Forum Contributor
Posts: 273
Joined: Wed Apr 13, 2005 1:53 am
Location: Detroit

Merge foreach statements?

Post 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";
        }
}
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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]"
facets
Forum Contributor
Posts: 273
Joined: Wed Apr 13, 2005 1:53 am
Location: Detroit

Post 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]">
Post Reply