PHP For Loop


The for loop will execute a block of code a specified number of times. It checks the condition and executes block of code for a specific number of times, until specified condition argument become false. The Syntax of for loop is :
 for (initialization; condition; iteration) {
   code block to be executed
 }
Where :
  • The initialization will initialize the counter to a starting value. The initialization statement is executed before the loop begins.
  • The condition will check if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
  • The iteration will increase or decrease your counter.

Lets see an example of for loop, the below code print "Hello world!" five times :
<?php
  for($count = 0; $count < 5; $count++) {
    echo "Hello world!<br/>";
  }
?>
Output :

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!

The below example the below code will print the table of 2.
<?php
  for($count = 1; $count <= 10; $count++) {
    echo $count*2 . "<br/>";
  }
?>
Output :

2
4
6
8
10
12
14
16
18
20


Next Topic :