Loop in PHP
Loop
Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
- for - loops : through a block of code a specified number of times.
- while - loops : through a block of code if and as long as a specified condition is true.
- do...while : loops through a block of code once, and then repeats the loop as long as a special condition is true.
- foreach : loops through a block of code for each element in an array.
Syntax
for (init; condition; increment)
{
code to be executed;
}
Syntax
for (init; condition; increment)
{
code to be executed;
}
Example
for ($i=1;$i<=10;$i++)
{
print(“<b>”.$i.”</b><br>”);
}
The init and increment parameters above can be empty or have multiple expressions (separated by commas).
The “while” Loop
Syntax
while (condition)
{
code to be executed;
}
Example
$num = 1;
while ( $num <=10 )
{
print $num . “<br>";
$num++;
}