If you write like this:

for($i = 0; $i<=0; $i++){ echo $i."<br>"; break; } echo $i; 

then the answer is:

 0 0 

And if so:

 for($i = 0; $i<=0; $i++){ echo $i."<br>"; } echo $i; 

then the answer is:

 0 1 

Why does this happen, unless, after an interrupt with the help of break shouldn't it be executed further $i++ ?

    3 answers 3

    Pay attention: http://php.net/manual/ru/control-structures.break.php break interrupts the execution - read it exits the construction of the cycle at the moment it stumbles upon it. In this case, the for loop increments only before the second pass of the loop. Accordingly, it does not work after the break statement.

    • In general, a break without conditions of type if (something is there) {break;} in a for loop does not make sense. Since it is easier to do without a cycle. It will be the same. - Ssssory

    The very meaning of the English word break is to interrupt, that is, to exit the cycle immediately.

    The opposite keyword has the continue keyword which also interrupts the current iteration of the loop, but returns control to the loop control statement to the part where $i++ is executed, and the loop will continue if the loop condition is still true.

      Pay attention to the structure of the for statement:

       for (initializer; condition; iterator) { body } 

      The break statement immediately completes the nearest outer loop or switch statement in which it appears. Control is transferred to the operator following the completed operator (if one exists). In this example, it goes beyond the cycle, i.e. variable increment does not occur.

      In the second case, there is no break statement, i.e. the body of the loop is executed while the condition expression is true.

      In order to interrupt the execution of the current iteration of the loop and move on to the next, the operator continue is used

      Important! First, an iterator is executed, and after it the condition is calculated. Iterator is executed only once - at the very beginning of the cycle, in front of all parts of the cycle. In this case, the iterator is skipped and the condition condition is checked.