PHP For loop


The for loop is a more complex loop in PHP with the following syntax:

for (expr1; expr2; expr3) {
    Statement
}

The following examples still output 1 to 10:

for ($ i = 1; $ i < = 10; $ i ++) {
    echo $ i;
}

Syntax Explanation

  1. The first expression (expr1) is evaluated unconditionally before the loop begins.
  2. expr2 is evaluated before each iteration of the loop. If the value is TRUE, the loop is continued and a nested loop statement is executed. If the value is FALSE, the loop is terminated.
  3. expr3 is evaluated (executed) after each iteration
  4. Each expression can be empty. If expr2 is empty, it will loop indefinitely, but you can end the loop with break:
    for ($ i = 1;; $ i ++) {
        if ($ i & gt; 10) {
            break;
        }
        echo $ i;
    }
    

Tip

In the use of loops, we usually have to pay attention to not infinite loop caused by the program "dead", also pay attention to the cycle conditions (loop to determine the expression) to ensure that the correct cycle results.




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook