Jakob
Jakob

Reputation: 3546

Continue loop inside loop

I have while loop inside another while loop and inside another while loop. This echoes products by categories and categories by groups. Simplified example code is below:

$a=0;
while(2 > $a) {
    echo "<div><h3>Group</h3>";
    $b=0;
    while(5 > $b) {
        echo "<label>Category</label>";
        echo "<select name='productID_".$b."'>";
        $c=0;
        while(10 > $c) {
            echo "<option>product</option>";
            $c++;
        }
        echo "</select><br/>";
        $b++;
    }
    echo "</div>";
    $a++;
}

What I need is that select name continues in another group and doesn't start from 0 again.
For example now if I have 2 groups with 2 product categories each then in first group select names will be productID_0 and productID_1 but in second group also. I need it in second to continue with productID_2 and productID_3.

How to do that?

Upvotes: 0

Views: 54

Answers (1)

Barmar
Barmar

Reputation: 780851

Use a different variable for the number in the HTML than you're using for the loop control:

$i = 0;
for ($a = 0; $a < 2; $a++) {
    echo "<div><h3>Group</h3>";
    for ($b = 0; $b < 5; $b++) {
        echo "<label>Category</label>";
        echo "<select name='productID_".$i."'>";
        $i++;
        for ($c = 0; $c < 10; $c++) {
            echo "<option>product</option>";
        }
        echo "</select><br/>";
    }
    echo "</div>";
}

BTW, for loops are the more usual idiom for looping like this, as it allows you to see the whole structure in one place.

Alternatively, you could use name='productID[]', rather than giving them distinct names. When the form is submitted, $_POST['productID'] will then contain an array of all the values.

Upvotes: 1

Related Questions