Controlling loop using break and continue with php sample
Probably this article is not talk about high level programming, but as programmer you will need to learn the basic of looping and how to control the loop. We will often use loop to iterate a code or an array to search or doing something. The traditional sintak of loop schema is while, do while, for or for each. This sintak is available on most programming languages.
In this article i will give loop example using php languages. PHP is the most web programming language that commonly use over the internet and web server. We use loop to do similar thing sequently, we call it also iterating a code or commonly iterating an array value.
For example to print number 1 until 10, we can use for statement.
for($i = 1; $i <= 10; $i++) echo $i;
Inside a loop we can put another loop or called as nested loop. When our application is become complicated, nested loop is often use. We commonly use nested loop to do a recursive iteration.
We need to control a loop, deciding the start point and the end point is a must. Without controlling it, you probably create never ending loop. for example this loop
$i = 0;
while($i <= 10){
//
}
To control a loop you need to mention start point and end point. Start point would be initial value for loop condition so the loop can start, for example $i= 0;. Next thing to remember is the end point. In this case $i > 10. So if true condition still valid, the loop still run.
Another control for loop is continue and break statement. Continue statement use to continue the loop to next iteration. In this case all code after break will not executed. I give you an example about how to print only odd number in range 1 until 10.
<?php
for($i = 1; $i <= 10; $i++){
if($i % 2 == 0) continue;
echo $i;
}
?>
On the other hand, break statement used for stoping current loop. For example we want to stop the loop when $total_number > 100;
<?php
$total = 0;
$i = 1;
while(true){
$total += $i;
if($total > 100) break;
$i++;
}
echo $total;
?>
When doing nested loop, we can set number of level that we want to break the nested loop. For example we want to break all loop from second loop, we can use break 2; means we break current loop and outhermost loop.
<?php
$a[0][0] = “a”;
$a[0][1] = “b”;
$a[1][0] = “y”;
$a[1][1] = “z”;
foreach ($a as $v1) {
foreach ($v1 as $v2) {
if($v2 == ‘y’) break 2;
echo “$v2\n”;
}
}
?>
This loop will break when $v2 == ‘y’.
I hope this simple tips can help you understanding on how to control a loop inside your application code. Keep improving your php skill by learning more. Good luck