Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by a number after "break" or "continue" in PHP?

Could someone please explain, with examples, what is meant by loop break 2 or continue 2 in PHP? What does it mean when break or continue is followed by a number?

like image 484
kn3l Avatar asked Mar 02 '11 12:03

kn3l


People also ask

What is the meaning of break and continue statements in PHP?

The break statement is used to jump out of a loop. The continue statement is used to skip an iteration from a loop.

What does break mean PHP?

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only. The break keyword immediately ends the execution of the loop or switch structure.

What is continue in PHP?

PHP Continue The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

What is difference between break and exit in PHP?

The PHP exit() terminates the execution of the current PHP script, whereas the break terminates the execution of the current loop or switch structure.


1 Answers

$array = array(1,2,3); foreach ($array as $item){   if ($item == 2) {     break;   }   echo $item; } 

outputs "1" because the loop was broken forever, before echo was able to print "2".

$array = array(1,2,3); foreach ($array as $item){   if ($item == 2) {     continue;   }   echo $item; } 

outputs 13 because the second iteration was passed

$numbers = array(1,2,3); $letters = array("A","B","C"); foreach ($numbers as $num){   foreach ($letters as $char){     if ($char == "C") {       break 2; // if this was break, o/p will be AB1AB2AB3     }     echo $char;   }   echo $num; } 

outputs AB because of break 2, which means that both statements was broken quite early. If this was just break, the output would have been AB1AB2AB3.

$numbers = array(1,2,3); $letters = array("A","B","C"); foreach ($numbers as $num){   foreach ($letters as $char){     if ($char == "C") {       continue 2;     }     echo $char;   }   echo $num; } 

will output ABABAB, because of continue 2: the outer loop will be passed every time.

In other words, continue stops the current iteration execution but lets another to run, while break stops the whole statement completely.
So we can ell that continue is applicable for the loops only, whereas break can be used in other statements, such as switch.

A number represents the number of nested statements affected.
if there are 2 nested loops, break in the inner one will break inner one (however it makes very little sense as the inner loop will be launched again in the next iteration of the outer loop). break 2 in the inner loop will break both.

like image 56
Your Common Sense Avatar answered Sep 21 '22 12:09

Your Common Sense