Looping in PHP
There are 2 standard types of while loops.
Type 1: while loop
eg.
<?php
$x = 0;
while ($x < 10) {
// do something
$x++;
}
?>
The conditional test is evaluated BEFORE the code block is executed.
Type 2: do ... while loop
eg.
<?php
$x = 0;
do {
// do something
$x++;
} while ($x < 10);
?>
The conditional test is evaluated AFTER the code block is executed.
This means that the code block is run a minimum of 1 time.
break and continue statements can affect looping if added in the code block.
break; abandons the while loop, and continues to the next statement.
continue; skips the current loop, but continues with the next loop.
eg.
<?php
$x = 0;
while ($x < 10) {
if ($x == 5) {
$x++;
continue;
}
if ($x == 8) {
break;
}
print($x . "<br>");
$x++;
}
?>
prints:
0
1
2
3
4
6
7
5 is missing as that iteration is skipped by continue;
8,9 are missing as break; terminated the loop when $x equals 8.
for loop statement:
eg.
<?php
for ($x=0; $x<10; $x++) {
if ($x == 5) {
continue;
}
if ($x == 8) {
break;
}
print($x . "<br>");
}
?>
prints the same results as above.
Type 1: while loop
eg.
<?php
$x = 0;
while ($x < 10) {
// do something
$x++;
}
?>
The conditional test is evaluated BEFORE the code block is executed.
Type 2: do ... while loop
eg.
<?php
$x = 0;
do {
// do something
$x++;
} while ($x < 10);
?>
The conditional test is evaluated AFTER the code block is executed.
This means that the code block is run a minimum of 1 time.
break and continue statements can affect looping if added in the code block.
break; abandons the while loop, and continues to the next statement.
continue; skips the current loop, but continues with the next loop.
eg.
<?php
$x = 0;
while ($x < 10) {
if ($x == 5) {
$x++;
continue;
}
if ($x == 8) {
break;
}
print($x . "<br>");
$x++;
}
?>
prints:
0
1
2
3
4
6
7
5 is missing as that iteration is skipped by continue;
8,9 are missing as break; terminated the loop when $x equals 8.
for loop statement:
eg.
<?php
for ($x=0; $x<10; $x++) {
if ($x == 5) {
continue;
}
if ($x == 8) {
break;
}
print($x . "<br>");
}
?>
prints the same results as above.

0 Comments:
Post a Comment
<< Home