leoarce
leoarce

Reputation: 549

keep counting up throughout multiple for loops

I have a loop within a loop like this:

//stuff here to determine what $my_var will be
for($i=0;$i<count($my_var);$i++) {
    //stuff here to determine what $anothervar will be
    for ($y = 1; $y <= $anothervar; $y++) {
        //help needed in here
        echo $y; //makes it so count starts over each time it goes around
    }
}

my_var is going to loop certain amount of times, not always the same amount.

The inner loop also is a random number.

An output could look like this:

1
    1,2
2
3
4
5
6
    1,2,3

So in first main loop the inner loop happened twice. in 6th main loop, the inner loop happened 3 times.

what i would like to do is instead of the inner loop starting over from 1 each time, i want it to keep counting up. so i want output to be like this:

1
    1,2
2
3
4
5
6
    3,4,5

Let's say the 3rd main loop has some inner loops in it, we'll make it 4 inner loops, then the output should be like this:

1
    1,2
2
3
    3,4,5,6
4
5
6
    7,8,9

How would I do a continuous count up in a loop within a loop?

EDIT

Here is what ended up working:

//stuff here to determine what $my_var will be
$y = 1;
for($i=0;$i<count($my_var);$i++) {
    //stuff here to determine what $anothervar will be
    for (; $y <= $anothervar; $y++) {
        //help needed in here
        echo $y; //this now continues to count up instead of starting over each main loop
    }
    $y = 1;
}

Upvotes: 0

Views: 82

Answers (2)

Alexander Baltasar
Alexander Baltasar

Reputation: 1054

$x = 0;
for($i=0;$i<count($my_var);$i++) {
    //stuff here to determine what $anothervar will be
    for ($y = 1; $y <= $anothervar; $y++) {
        $x++;
        echo $x; // now x is incremented every inner loop by 1
    }
}

Just changed 3 lines of your first code example.

Upvotes: 1

miken32
miken32

Reputation: 42715

Wherever you see $y = 1 you're setting it back to 1. So if you want it to continue increasing, don't do that – except at the beginning, outside the loop.

$y = 1;
for($i=0;$i<count($my_var);$i++) {
    //stuff here to determine what $anothervar will be
    for (; $y <= $anothervar; $y++) {
        //help needed in here
        echo $y; //this now continues to count up instead of starting over each main loop
    }
}

Upvotes: 0

Related Questions