Loops in PHP

PHP Loops
  • when you write code, you want the same block of code to run over and over again a certain number of times. So, we can use loops.
  • Loops are used to execute the same block of code again and again.
  • Loops types are given below.
  • for loop
  • foreach loop
  • while loop
  • do...while loop
  • Break and Continue
PHP for loop
  • The for loop is used to Loops through a block of code a specified number of times.
  • The for loop is used when you know in advance how many times the script should be output the script.
  • Syntax - for loop
  • for (initialization; condition; increment or decrement){
    //code to be executed;
    }

    • init counter: Initialize the loop counter value
    • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
    • increment counter: Increases the loop counter value


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