MENU
Loops
There are several ways to run a block of statements repeatedly:while(cycle condition){statements;}
do {statements;} while(cycle condition);
for (pre-loop statements;
cycle condition;
cycle statements;){statements;}
foreach ($array as $value){statements;}
foreach($array as $key => $value){statements;}
Each of these code segments calculates the sum of 0 to 9.
foreach is used to loop through the values of an array or class object.
$a=0; $sum=0;
while ($a<10) $sum+=$a++;
$a=0; $sum=0;
do {$sum+=$a++;}
while ($a<10);
for ($a=0,$sum=0;$a<10;$a++) $sum+=$a;
The reference, '&' , allows the values in the array to be changed. Note that the variables retain their last values after the loop.
break [i]; ends the loop instantly. continue [i]; ends the current iteration of loop and starts the next iteration by evaluating the cycle condition. i is an optional integer that tells how many levels of loops to end. If omitted, it will be regarded as 1, ie. the current level.
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$a=[3,4,"foo"=>5,6,100];
foreach($a as $k => &$v) {
$v*=2;
echo $k.$v."<br />";
}
echo $k.$v."<br />";
foreach($a as $v2) {
echo $v2."<br />";
}
?></body>
</html>
06 18 foo10 212 3200 3200 6 8 10 12 200
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
for ($a=0; $a<5; $a++){ // level 3 for continue
for ($b=0; $b<5; $b++){ // level 2 for continue
for ($c=0; $c<5; $c++){ // level 1 for continue
echo ($a+$b+$c).",";
if ($a+$b+$c>5) continue 3;
}
echo "<br />";
}
if ($a>3) break;
}
?></body>
</html>
This calculates the sum of 0 to 9.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html>
<html>
<head></head>
<body><?php
$i=0; $sum=0;
sectionA:
$sum+=$i++;
if ($i<10) goto sectionA;
echo $sum;
?></body>
</html>