The for loop is used when you know in advance how many times the scripts should run.
Syntax:
for (initialization; condition; increment/decrement)
{
code to be executed;
}
sample code:
<?php
for ($i=1; $i<=15; $i++)
{
echo “The result is: ” . $i . “<br />”;
}
?>
The foreach loop is used to loop through arrays.
Syntax:
foreach ($array as $value)
{
code to be executed;
}
sample code:
<?php
$x=array(“uno”,”dos”,”tres”);
foreach ($x as $value)
{
echo $value . “<br />”;
}
?>
The while loop executes a block of code while a condition is true.
Syntax:
initialization;
while (condition)
{
code to be executed;
increment/decrement;
}
sample code:
<?php
$i=1;
while($i<=10)
{
echo “The result is: ” . $i . “<br />”;
$i++;
}
?>
The do…while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.
Syntax:
initialization;
do
{
code to be executed;
increment/decrement;
}
while (condition);
sample code:
$i=1;
do
{
$i++;
echo “The result is: ” . $i . “<br />”;
}
while ($i<=5);
?>
Recent Comments