Tutorials

PHP for beginners -Lesson 7

Sending
User Rating 5 (1 vote)

INTERRUPTING LOOPS(break and continue) IN PHP
 
1. Break keyword
    The PHP break keyword is used to terminate the execution of a loop prematurely.
    Once break statement executed , it immediately terminates the loop and no further iterations are made.
  In the following example the condition test becomes true when the counter value reaches  five:
    <?php
    $i=1;
    while($i <= 10){
        
        echo $i."\t";
        
        if($i == 5) break;
        
        $i++;
    }
    echo "<br/>Iteration stopped at $i by break statement";
?>
Output:
1 2 3 4 5
Iteration stopped at 5 by break statement

General use of break statement..
    a) Searching a record within a loop : After matching condition you can put break statement to terminate the loop, which save your extra loop execution time.
    b) If we wanted to display top 10 records from 1000 of list.
    
 
2. Continue keyword
    The PHP continue keyword is used to halt the current iteration of loop but it does not terminate the loop.
    When condition is true, the continue statement immediately stop the next line of execution and go to test condition loop again.
    
    Example </pre> <?php
    for($i=1; $i<=10; $i++){
            
        if($i == 5)
            continue; // When $i value become 5, its going to check loop condition again rather than executing next line.
        
        echo $i."\t";
        
    }
    echo "<br/>Iteration stopped at $i";
?>    
Output:        
1 2 3 4 6 7 8 9 10  
Iteration stopped at 11

General use of continue statement..
    Suppose, you want to display all student list who got above and equal 30 percent  
         <?php
        if($percentage < 30)
            continue;
        //Display Student information here
    ?>
Note : Break and continue situated inside loop(for, while, do-while or foreach) only.

Share your Thoughts