break and continue

Introduction

In PHP and many other programming languages, loops are used to repeat a block of code multiple times. Sometimes, we need more control over how a loop behaves. This is where the break and continue statements are used. They help control the flow of loops based on specific conditions.

What is Break Statement

The break statement is used to completely stop a loop before it finishes its full cycle. When break is executed, the loop ends immediately and the program moves to the next statement outside the loop.

Example of Break Statement

<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i;
}
?>

In this example, the loop stops when the value of i becomes 5.

What is Continue Statement

The continue statement is used to skip the current iteration of a loop and move to the next iteration. It does not stop the loop completely.

Example of Continue Statement

<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
continue;
}
echo $i;
}
?>

In this example, the number 5 is skipped, but the loop continues until 10.

Difference Between Break and Continue

Break stops the entire loop immediately
Continue skips only one iteration and continues the loop

Real World Use of Break and Continue

Break is used when a condition is met and further looping is unnecessary such as searching for a value and stopping when found
Continue is used when certain values need to be ignored such as skipping invalid or unwanted data in a list

Advantages of Break and Continue

They improve control over loops
They make code more efficient
They help handle conditions more cleanly
They reduce unnecessary processing

Conclusion

Break and continue are powerful loop control tools in PHP. They help developers manage loop execution more efficiently and build smarter logic in programs.

Home Ā» PHP Fundamentals (Beginner Level) > Loops > break and continue