PHP For Loops

Instead of executing a task again and again, using loop is an efficient way of executing task in programming / Scripting world.

FOR LOOP:

For loop, as name says, looping a task until unless a condition is met.

Syntax:

for(initial value; condition; increment/decrement){

//execute required task 

}

To better understand the syntax, lets take one example.

Suppose I want to print 1 to 10 on the webpage. So the code is as below.

<?php

echo 1;

echo 2;

echo 3;

echo 4;

echo 5;

echo 6;

echo 7;

echo 8;

echo 9;

echo 10;

?>

The above code is going to print 1 to 10.

What if , I am required to print 1 to 1000. It would be time consuming process. So for such scenario, we use for loop. Using for loop we can execute any number of task.

Lets print 1 to 100 using for loop.

Before using for loop, we have to ready with following three factors:

  1. Starting value (here starting value is 1)
  2. condition (Up to what value we want to print value. Here we want to print upto 100. The condition would be: less than 101 or less than equal to 100)
  3. Upon completion of a loop, what it should do? (In our example, upon completion of each loop, we want to increment the value by 1)

In our example, starting value is 1. It should loop until the value 100 is printed. Therefore the condition is the loop should keep looping until 100 is printed. At the end of the each loop, it should increase the value by 1.

The code would be as below:

<?php

for($i=1; $i<=100; $i++){

echo $i;

}

?>

The above code would print 1 to 100. See, for loop saved our time and effort. To print 1 to 100, we could have typed 100 echo statements. But just three lines did the job. This is the power of for loop.

So what is happening in this for loop block?

This way, for loop works.

Warning: if you forget to mention the condition, then the loop lands in infinite loop. Because for loop only stops when a condition did not meet. If we don’t mention the condition then, it would go into infinite loop. So be careful while using for loop. 

Assignment: