0

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?

2
  • Don't reset $b to 0 every time through the outer loop. Commented Feb 27, 2015 at 0:52
  • I know thats the problem but don't know how to solve it Commented Feb 27, 2015 at 0:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried that but then my second group is not echoed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.