Break and Continue in PHP

PHP Break
  • PHP break is used to "jump out" of a out of a loop, alredy seen in switch statement.
  • The foreach loop works only on arrays, and is used to loop through each value pair in an array.
  • example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    for ($a = 0; $a < 20; $a++) {
    if ($a == 5) {
    break;
    }
    echo "number: $a </br>";
    }
    ?>
    </body>
    </html>
    
PHP Continue
  • PHP continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
  • example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    for ($a = 0; $a < 5; $a++) {
    if ($a == 2) {
    continue;
    }
    echo "number: $a </br>";
    }
    ?>
    </body>
    </html>
    
PHP break and Continue example
    <!DOCTYPE html>
    <html>
    <body>
    <?php
    $a = 0;
    while($a < 10) {
    if ($a == 4) {
    break;
    }
    echo "number: $a </br>";
    $a++;
    }
    ?>
    </body>
    </html>
    


  • example
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    $a = 0;
    
    while($a < 5) {
    if ($a == 2) {
    $a++;
    continue;
    }
    echo "number: $a </br>";
    $a++;
    }
    ?>
    </body>
    </html>
    
Related Posts :