Friday, 19 September 2014

for Loops in PHP

PHP provides C-style for loops. The for loop accepts three arguments:
for (start_expressions; truth_expressions; increment_expressions)
Most commonly, for loops are used with only one expression for each of the start, truth, and increment expressions, which would make the previous syntax table look slightly more familiar.
The start expression is evaluated only once when the loop is reached. Usually it is used to initialize the loop control variable. The truth expression is evaluated in the beginning of every loop iteration. If true, the statements inside the loop will be executed; if false, the loop ends. The increment expression is evaluated at the end of every iteration before the truth expression is evaluated. Usually, it is used to increment the loop control variable, but it can be used for any other purpose as well. Both break and continue behave the same way as they do with while loops. continue causes evaluation of the increment expression before it re-evaluates the truth expression.

Statement

for (expr, expr, …; expr, expr, …; expr, expr, …)
statement
Statement List
for (expr, expr, …; expr, expr, …; expr, expr, …):
statement list
endfor;

Statement

for (expr; expr; expr)
statement
Statement List
for (expr; expr; expr):
statement list
endfor;
Here’s an example:
for ($i = 0; $i < 10; $i++) {
print "The square of $i is " . $i*$i . "\n";
}
The result of running this code is
The square of 0 is 0
The square of 1 is 1
...
The square of 9 is 81
Like in C, it is possible to supply more than one expression for each of the three arguments by using commas to delimit them. The value of each argument is the value of the rightmost expression.
Alternatively, it is also possible not to supply an expression with one or more of the arguments. The value of such an empty argument will be true. For example, the following is an infinite loop:
for (;;) {
print "I'm infinite\n";
}
Tip: PHP doesn’t know how to optimize many kinds of loop invariants. For example, in the following for loop, count($array) will not be optimized to run only once.
for ($i = 0; $i <= count($array); $i++) {
}
It should be rewritten as
$count = count($array);
for ($i = 0; $i <= $count; $i++) {
}
This ensures that you get the best performance during the execution of the loop.

0 comments:

Post a Comment