break
and continue
statementsbreak
statement in a while
loopwhile (true) { $number = mt_rand(1, 10); if ($number % 2 == 0) { break; // exits the while loop and executes the echo statement next } } echo("<p>\$number is: $number</p>\n"); // $number is between 1 and 10 and even
$number is: 8
break
statement in a for
loop$number = 13; $prime = true; for ($i = 2; $i < $number; $i++) { if ($number % $i == 0) { $prime = false; break; // exits for loop and executes the $result statement next } } $result = ($prime) ? ' is ' : ' is not '; echo("<p>$number $result prime</p>\n");
13 is prime.
for
loopecho("<p>"); for ($number = 1; $number <= 10; $number++) { if ($number % 3 == 0) { continue; // returns to start of for loop when number is not evenly divisable by 3 } echo("\$number is not divisible by 3"); } // Only displays 1, 2, 4, 5, 7, 8, and 10 echo("</p>\n");
1 is not divisible by 3.
2 is not divisible by 3.
4 is not divisible by 3.
5 is not divisible by 3.
7 is not divisible by 3.
8 is not divisible by 3.
10 is not divisible by 3.
while
loop$number = 1; echo("<p>"); while ($number <= 10) { if ($number % 3 == 0) { $number++; continue; // returns to start of for while when number is not evenly divisable by 3 } echo("$number<br />"); $number++; } // Only displays 1, 2, 4, 5, 7, 8, and 10 echo("</p>\n");
1 is not divisible by 3.
2 is not divisible by 3.
4 is not divisible by 3.
5 is not divisible by 3.
7 is not divisible by 3.
8 is not divisible by 3.
10 is not divisible by 3.
break
statement ends a loop. In other words, it jumps out of the loopcontinue
statement ends the current iteration of a for or while loop, but allows the next iteration to proceed. In other words, it jumps to the start of the loop.break
and continue
statements apply only to the loop that they’re in.