[ Pobierz całość w formacie PDF ]
.forPodręcznik PHPPoprzedniRozdział 11.Control StructuresNastępnyfor
for loops are the most complex loops in PHP.They behave like their C counterparts.The syntax of afor loop is:for (expr1; expr2; expr3) statement
The first expression (expr1) isevaluated (executed) once unconditionally at the beginning of theloop.
In the beginning of each iteration,expr2 is evaluated.If it evaluates toTRUE, the loop continues and the nestedstatement(s) are executed.If it evaluates toFALSE, the execution of the loop ends.
At the end of each iteration, expr3 isevaluated (executed).
Each of the expressions can be empty.expr2 being empty means the loop shouldbe run indefinitely (PHP implicitly considers it asTRUE, like C).This may not be as useless asyou might think, since often you'd want to end the loop using aconditional breakstatement instead of using the for truthexpression.
Consider the following examples.All of them display numbers from1 to 10:/* example 1 */for ($i = 1; $i <= 10; $i++) {print $i;}/* example 2 */for ($i = 1;;$i++) {if ($i > 10) {break;}print $i;}/* example 3 */$i = 1;for (;;) {if ($i > 10) {break;}print $i;$i++;}/* example 4 */for ($i = 1; $i <= 10; print $i, $i++);
Of course, the first example appears to be the nicest one (orperhaps the fourth), but you may find that being able to use emptyexpressions in for loops comes in handy in manyoccasions.
PHP also supports the alternate "colon syntax" forfor loops.for (expr1; expr2; expr3): statement;.; endfor;
Other languages have a foreach statement totraverse an array or hash.PHP 3 has no such construct; PHP 4 does(see foreach).In PHP 3, youcan combine whilewith the list() and each()functions to achieve the same effect.See the documentation forthese functions for an example.PoprzedniSpis treściNastępnydo.whilePoczątek rozdziałuforeach
[ Pobierz całość w formacie PDF ]