php break and continue statement

The break statement
The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and
whenever you want to exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed.

Example
In the following example condition test becomes true when the counter value reaches 3 and
loop terminates.

<html>
<body>
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>

This will produce following result:
Loop stopped at i = 3


The continue statement
The PHP continue keyword is used to halt the current iteration of a loop but it does not
terminate the loop.
Just like the break statement the continue statement is situated inside the statement block
containing the code that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass starts.

Example
In the following example loop prints the value of array but for which condition becomes true it
just skip the code and next value is printed.

<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )continue;
echo "Value is $value <br />";
}
?>
</body>
</html>

This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5
Previous
Next Post »