PHP Break , Continue and Goto
Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.
Break - ends execution of the current structure. Break accepts an optional numeric argument which tells it how many executions of nested structures to be interrupted.
<?php
$x = 0 ;
while($x)
{
echo($x . " ");
if($x == 5)
{
break;
}
$x ++ ;
}
// output 0 1 2 3 4 5
?>
Example with the argument:
<?php
$x = 2 ;
while($x)
{
for($j =0 ; $j ++)
{
echo $j * $x ;
if($j * $x >= 10)
{
break 2;
}
}
$x ++ ;
}
// output 0 2 4 6 8 10
?>
Continue - is used to stop processing the current block of code in the loop and goes to the next iteration.
<?php
for($i = 0; $i < 5; $i ++)
{
if($x == 2)
{
continue;
}
echo $i . " ";
}
// output 0 1 3 4
?>
The Continue statement, as well as the Break, can take an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
Php also supports operator goto - which is the operator of unconditional transition. It used to go into another area of the code. A place where you must go to the program is indicated by the label (a simple identifier), followed by a colon. For the transition after the goto statement is put the desired label.
<?php
for($i = 0; $i < 5; $i ++)
{
if($x == 2)
{
goto end;
}
echo $i . " ";
}
end:
?>
// output 0 1
Operator goto has some limitation
The target label must be within the same file and context, which means that you cannot jump out of a function or method. You also cannot jump into any loop or switch structure. You may jump out of these .