PHP break statement and continue Example

By | 2018-04-01T10:39:19+00:00 January 24th, 2017|PHP|0 Comments

In this tutorial we are going to learn about php break statement and continue and those importances.

PHP break statement :

A break statement is useful when we wants to exit from a loop without completing the iteration.

The keyword break is used universally to get out of loops in PHP. It works for the for, foreach, switch statements, and while statements.


<?php
$apples = array(100, 200, 1100, 300, 600);
$v1 = 0;
$sum = 0;
while ($v1 <= 5) {
if ($sum > 1400) {
break;
}
$sum = $sum + $apples[$v1];
$v1 = $v1 + 1;
}
echo $sum;
?>

Output:

1700

On the above example, the break statement is executed when ever the $sum value is greater then 1400.

PHP Continue Statement :

This statement is used when the developer directs control to the beginning of a loop, effectively skipping other statements inside the loop.

The keyword continue is used. It is also associated with the if statements.


<?php

$x = 1;
echo 'even numbers upto 10<br />';
while ($x <= 10) {
if ($x % 2) {
$x++;
continue;
} else {
echo $x . '<br />';
$x++;
}
}

Output:

even numbers upto 10
2
4
6
8
10

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment