Google News
logo
PHP Program to break statement in a loop
The `break` statement is used in PHP loops to exit the loop prematurely. When a `break` statement is encountered inside a loop, the loop is immediately terminated, and program execution continues with the statement immediately following the loop.

Here's an example of a `for` loop that uses a `break` statement to exit the loop early :
Program :
<?php
    // This is a PHP program that uses a for loop with a break statement
    
    for ($i = 1; $i <= 10; $i++) {
        if ($i == 5) {
            break;
        }
        echo $i . " ";
    }
?>
Output :
1 2 3 4
In this code, the `for` loop initializes the variable `$i` to `1`, and increments `$i` by `1` after each iteration. Inside the loop, there is an `if` statement that checks if `$i` is equal to `5`.

If `$i` is equal to `5`, then the `break` statement is executed, which causes the loop to terminate early.

When `$i` is equal to `5`, the `break` statement is executed, and the loop terminates. The program then continues with the statement immediately following the loop, which in this case is nothing.

This demonstrates how the `break` statement can be used to exit a loop prematurely, based on a condition that is evaluated inside the loop.