I am aware we can skip the next iteration with continue in a for loop. Anyway to skip the next x loops (2 or more)?
Asked
Active
Viewed 1,196 times
3
-
1For reference continue does not skip the next iteration, it ends the current one. – Jonnix May 06 '16 at 14:22
-
You can try defining an extra integer, set it to the amount of loops you want to skip and have an `if ( y < 0) { continue; }` type of thing – May 06 '16 at 14:22
-
2You can try to use continue; and i+=10; to skip more iterations? – R Pelzer May 06 '16 at 14:24
-
Can you provide the code where you would need this? – trincot May 06 '16 at 14:29
4 Answers
6
You actually can't, you can do a dirty trick like
for ($i=0; $i<99; $i++){
if(someCondition) {
$i = $i + N; // This will sum N+1 because of the $i++ in the for iterator (that fire when the new loop starts)
continue;
}
}

Gumma Mocciaro
- 1,205
- 10
- 24
1
If you're iterating with a for loop (as opposed to a foreach loop) you could do something like this:
for ($i=0; $i<$numLoops; $i++) {
if(condition()) {
$i+= $numLoopsToSkip;
continue;
}
}

Michael Ambrose
- 992
- 6
- 11
-
You need to add one less to *i*. Adding 0 would still interrupt the current iteration. – trincot May 06 '16 at 14:30
1
Take for example, you can define the amount of times you want to loop as you want as $y
<?php
y = 5;
while (true) {
// do something
if (y > 0) {
y--;
continue;
}
// do something else
}
?>
-
1I think this will generate an ugly loop, ```y``` is never decreased, so it will always be > 0 – Gumma Mocciaro May 06 '16 at 14:31
-
0
Coming soon in PHP 'X' ;-)
continue += x;

Anthony Rutledge
- 6,980
- 2
- 39
- 44
-
If this is even a good idea (reference: Edsger W. Dijkstra), I hope it would be this simple. – Anthony Rutledge May 06 '16 at 14:35