PHP Break and Continue Statements :-
- The Break Statement :-
- The PHP break keyword is used to terminate the execution of a loop prematurely.
- By using break statement/keyword, whenever we want to exit from the loop we can come out.
- After coming out of a loop, the immediate statements to the loop will be executed.
- It can be example further with a suitable example:-
break.php:-
<html>
<body>
<?php
$i = 0;
echo "The value of <b>i:-</b><br/><br/>";
while( $i < 5)
{
$i++;
echo "<b>$i</b><br/>";
if( $i == 3 )
break;
}
echo "<br/>";
echo "<b> Break is used </b><br/><br/>";
echo ("Loop stopped at i = <b> $i </b>" );
?>
</body>
</html>
Screenshot:-
- The Continue Statement :-
- The continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
- If we used the continue keyword, rest of the loop code is skipped and next pass starts.
- With a suitable example, it can be understand properly:-
continue.php:-
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
echo "Array's Data is <b> $array[0] </b> <br/>";
echo "Array's Data is <b> $array[1] </b> <br/>";
echo "Array's Data is <b> $array[2] </b> <br/>";
echo "Array's Data is <b> $array[3] </b> <br/>";
echo "Array's Data is <b> $array[4] </b> <br/><br/>";
echo "<b><i>Continue is used, when i's value is equal to 3</i></b>";
echo "<br/><br/>";
echo "<br/><br/>";
echo "So, now the value is:-<br/>";
foreach( $array as $value )
{
if( $value == 3 )
continue;
echo "<b>$value</b> <br />";
}
?>
</body>
</html>
Screenshot:-
No comments:
Post a Comment