Difference Between Break and Continue in PHP

Difference between break and continue in PHP?

break ends a loop completely, continue just shortcuts the current iteration and moves on to the next iteration.

while ($foo) {   <--------------------┐
continue; --- goes back here --┘
break; ----- jumps here ----┐
} |
<--------------------┘

This would be used like so:

while ($droid = searchDroids()) {
if ($droid != $theDroidYoureLookingFor) {
continue; // ..the search with the next droid
}

$foundDroidYoureLookingFor = true;
break; // ..off the search
}

PHP - Difference between break and continue in switch case

Here is a simple example code with both the switch cases mentioned above

<?php
$variable = 20;
echo "Normal<br/>";
switch ($variable) {
case '20':
echo "twenty";
break;
case '21':
echo "twenty one";
break;
}

echo "<br/><br/>With Continue<br/>";
switch ($variable) {
case '20':
echo "twenty";
continue;
case '21':
echo "twenty one";
continue;
}
?>

When I execute above code I got following output

Normal
twenty

With Continue
twenty

How?

Working of break statement

Break statement causes code execution to come out of the block and execute next statements because of which switch statement will execute only one case statement and exit out of switch block without executing other case blocks.

Working of Continue statement

Continue statement in case of loops will cause loop to stop execution of current iteration of loop and go for next iteration of the loop(if any exists) but in case of switch statement it is considered as a loop statement but no next iterations causing exit switch statement.

We can have a switch statement without break statements too like this

<?php
$variable = 20;
echo "Normal";
switch ($variable) {
case '19':
echo "<br/>Nineteen";
case '20':
echo "<br/>twenty";
case '21':
echo "<br/>twenty one";
case '23':
echo "<br/>twenty three";
}
?>

The output of above code will be

Normal
twenty
twenty one
twenty three

i.e. executing all the case statements after the case where first match is found.

difference between continue 2 and break in nested loops

In this particular example it seems that it's the same thing and it is up to you to decide how you prefer it. One reason I can see to keep continue 2 would be if in a future development of your project you would add something after the inner for

for($rows as $i){
for($columns as $j){
if( Helper::unicornExists($i, $j) ){
//continue 2;
break;
}
}
echo 'done with ', $i, PHP_EOL;
}

You need to think what you expect if the unicorn does exist. Do you want to skip just the inner loop, and that's what break would do, or you want to skip the outer one also, and that's what continue 2 would do.

Break, continue and exit issue while using with loop PHP 5.6

break ends execution of the current for, foreach, while, do-while or switch structure.

break 1 will only break out of your "switch" statement, you will need break 2 to reach the while loop nesting level.

$count = 0;
while( $count++ < 10 )
{
echo 'while';
switch( true )
{
case true:
echo 'switch';
break 2; // TWO is needed here to break out of TWO levels of nesting
}
}

https://www.php.net/manual/en/control-structures.break.php

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

break; vs continue; vs return;

Using keywords such as break and continue can make the code far easier to read than what you propose.

Especially if you are nesting if/else-statements more than one level.

Compare the snippets further down in this post, which one is easier to read?
Both of them output the same exact thing, and $A is array (1,2,4,4,3,4).

A return in a loop (inside a function) can save precious CPU cycles, if you know you don't need to loop any further, why do it?



I'm too cool to use break/continue..

$not_even_found = false;

foreach ($A as $v) {
if ($v != 1) {
if ($not_even_found) {
} else if ($v % 2 != 0) {
$not_even_found = true;
} else {
echo "$v\n";
}
}
}


I want to have readable code..

foreach ($A as $v) {
if ($v == 1)
continue;

if ($v % 2 != 0)
break;

echo "$v\n";
}

break if statement and continue loop

@Nigel Ren already commented what I was going to say but I'm adding it as an answer anyway. If statements don't need a break or continue. Look at this example:

foreach(...) {
if(condition) {
//will work only if the condition is true
} else {
//will work if the condition is not true
}

//will always work (after if-else block) as long as the loop continues
}

continue 2 and break in switch statement

The continue 2 skips directly to the next iteration of the structure that is two levels back, which is the foreach. The break (equivalent to break 1) just ends the switch statement.

The behavior in the code you've shown is:

Loop through $elements. If an $element is type "a" and condition1 is met, or if it's type "b" and condition2 is met, skip to the next $element. Otherwise, perform some action before moving to the next $element.


From PHP.net:continue:

continue accepts an optional numeric argument which tells it how many
levels of enclosing loops it should skip to the end of. The default
value is 1, thus skipping to the end of the current loop.


From PHP.net:switch

PHP continues to execute the statements until the end of the switch
block, or the first time it sees a break statement.

If you have a switch inside a loop and wish to continue to the next
iteration of the outer loop, use continue 2.

Continue or break a specific loop

It is not possible. Furthermore, too many break-Statements can make your code very unreadable and hard to understand. You should restructure your code to avoid breaks and use other control flow statements.

do {
$i += 1;
if($i === 5) {
echo "At 5<br />\n";
} else if ($i === 10) {
echo "At 10; quitting<br />\n";
}
} while($i < 10);

You can also try to split your code up in different functions or methods.

function doSomething($i) {
if($i === 5) {
echo "At 5<br />\n";
} else if ($i === 10) {
echo "At 10; quitting<br />\n";
}
}

function run() {
$i = 0;
while($i < 10) doSomething(++$i);
}

In the second case you have to be aware of the strong dependency between the two functions. If you would change run() so that it counts to 15 the function doSomething would misbehave if $i = 10. Therefore you should encapsulate them in a class or try to introduce another variable which both functions can use to determine when the loop will end. That will avoid future mistakes and magic things to happen.

function doSomething($i, $max) {
if($i === 5) {
echo "At 5<br />\n";
} else if ($i === $max) {
echo "At 10; quitting<br />\n";
}
}

function run($max) {
$i = 0;
while($i < $max) doSomething(++$i);
}

Of course it is no problem to use one, two or even more breaks if your code remains readable. But you should consider if there are other more elegant ways to solve your problem. And mostly there are better ways.



Related Topics



Leave a reply



Submit