You are on page 1of 3

LOOPS IN PHP

FOR -LOOP The structure of the for loop is similar to that of the if statement <? php for() { } ?> Inside the normal bracket we will put the condition, while between the curl brackets we will write the commands we wish to be executed. There are three conditions first is to set up an initial condition, the second condition is to set up the condition for the loop to continue, the last thing is that makes the condition to execute several times or sometimes it means increment or decrement. Example 1 <? php for($i=0; $i<10; $i++)

{ echo $i."<br>"; } ?> The above example we set up an initial variable to be zero then the number to be printed should be less than 10 then $i++ indicates that the number should increase by 1. So everytime the number 1 will be added to i up to 9.

Example 2 <?php for($i=12; $i<24; $i+=2) { echo $i."<br>"; } ?> Form the above example the initial value is 12 and it will keep on increasing by 2 but the last number will be less than 24. This means that the output of this program will be 12, 14, 16, 18, 20, 22 Example 3 <?php for($i=12; $i<24; $i-=2) { echo $i."<br>"; } ?>

The above example we want to execute all numbers less than 24 but these numbers will be decreasing by 2, you know what will happen? Some of the browser will not display any thing since the values will be decreasing to infinity. What is the solution to such problem, then we need to change the condition and then the codes will look as follows Example 4 <?php for($i=24; $i>12; $i-=2) { echo $i."<br>"; } ?> From the above example the output will 24, 22, 20, 18, 16, 14, 12.

Thanks for visiting www.pox10.blogspot.com Any problem mail to: jacobmwaipopo@gmail.com

You might also like