A for
loop in PHP is a control structure that executes a block of code repeatedly for a fixed number of times. It has the following syntax:
for (initialization; condition; increment/decrement) { // body }
These four parts of a PHP for
loop are executed in the following order:
- Initialization: The initialization expression is executed first. It initializes the loop counter variable to the starting (or initial) value. This step is executed only once (i.e. at the beginning of the loop).
- Condition: The condition expression is evaluated next. If the condition is evaluated to
true
, then the loop continues to execute; otherwise, the loop terminates. The condition is evaluated before each iteration of the loop. - Body: The block of code inside the
for
loop is executed next. This code is executed repeatedly, in each iteration, until the loop terminates. The body of the loop can contain any valid PHP code, including other loops, conditional statements, and function calls. - Increment/Decrement: The increment or decrement expression is executed last (i.e. at the end of each iteration). This expression updates the loop counter variable. After the expression is executed, the loop returns to step 2 and re-evaluates the condition.
The steps mentioned above are repeated until the condition evaluates to false
— in which case, the loop is terminated, passing the control to the next statement after the for
loop.
It's important to note that the order of execution is always the same in a for
loop, regardless of the specific implementation or the complexity of the loop body.
For example:
for ($i = 0; $i < 5; $i++) { echo $i; // 0 1 2 3 4 }
In this example, the variable $i
is initialized to 0
, and the loop executes until $i
is less than 5
. If the loop condition evaluates to false
, then the loop is terminated. Otherwise, the body of the loop is executed, and right after, the increment/decrement expression is evaluated. Thus, in this case, the loop outputs 0 1 2 3 4
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.