Читать книгу PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO) - Sergey D Skudaev - Страница 12
The for loop
Оглавлениеfor ($i=0; $i <10; $i++) {
print ($i.”<br>”);
}
The $i variable is local because it is defined inside the loop. However, if you try to Output: the $i variable outside the loop, its value will be 10.
Break and Continue
Break; statement breaks out of the loop. Loop execution stops.
$names [0] =“Anna”;
$names [1] =“George”;
$names [2] =“James”;
$names [3] =“James”;
$names [4] =“John”;
$names [5] =“Maria”;
$names [6] =“Peter”;
$names [7] =“Robert”;
for ($i=0; $i <sizeof ($names); $i++) {
if ($names [$i] == “John”)
Break;
print ($names [$i].”<br>”;
}
The loop above will print the names:
Anna
George
James
James
and then stops. The names John, Maria, Peter and Robert will not be printed.
Continue; statement makes the loop skip iteration. See the following continue code example:
for ($i=0; $i <sizeof ($names); $i++) {
if ($i == 0)
print ($names [$i].”<br>”);
else
{
if ($names [$i-1] == $names [$i])
continue;
print ($names [$i].”<br>”);
}
}
Output:
Anna
George
James
John
Maria
Peter
Robert
In line if ($names [$i-1] == $names [$i]) we check if a previous name equals a current name. In the first iteration, we do not have a previous name, so we print a name without checking for a duplicate.
Starting from the second iteration, when $i => 1 we check whether a previous name is equal to the current one. If it is, we skip the loop.
As a result, the duplicate name is not printed. The break and continue may be used in all other loops.