Loops are set of instructions that repeat elements in specific number of times.
Counter variable is used to increment or decrement with each repetition of
the loop. The two major groups of loops are, For..Next and While..Loop.
The For statements are best used when you want to perform a loop in specific number of times. The Do and While statements are best used to perform a loop an undetermined number of times.
This is a For..Next example which counts from 1 to 5.
<?php
for($x=1;$x<6;$x++)
{
print("The x is: ".$x."<br>");
}
?>
Execution result:
The x is: 1 The x is: 2 The x is: 3 The x is: 4 The x is: 5
The above example increments a variable counter from 1 to 5
The values of x are incremented by 1 on each run before 6.
The following example will multiply value of x in above example by 2 on each run.
<?php
for($x=1;$x<6;$x++)
{
print("The value of $x by 2 is: ".($x*2)."<br>");
}
?>
The value of 1 by 2 is: 2 The value of 2 by 2 is: 4 The value of 3 by 2 is: 6 The value of 4 by 2 is: 8 The value of 5 by 2 is: 10
While and Do While
The Do..While structure repeats a block of statements until
a specified condition is met.
While performs a loop statement as long
as the condition being tested is true. Each run of the code block in a loop is called an iteration.
The following is a example of While loop statement to accomplish previous example:
<?php
$x=1;
while ($x<6)
{
print"The x is: ".$x."<br>";
$x++;
}
?>
Execution result:
The x is: 1 The x is: 2 The x is: 3 The x is: 4 The x is: 5
You can also accomplish the loop this way by using Do..While:
<?php
$x=1;
Do
{
print"The x is: ".$x."<br>";
$x++;
} while($x<6)
?>
Execution result:
The x is: 1 The x is: 2 The x is: 3 The x is: 4 The x is: 5
Nested Loop Statement
A nested loop statement is a loop within a loop.
It's usefull when accomplishing parent/child related records similar to car and it's inforation as wes seen
in the array session. The following example is using 2 demmitional arrays and nested loop statement: