What Are the Parts of a for Loop in PHP?

The PHP for loop has three parts in its header:

for (initialization; condition; increment/decrement) {
    // body
}

These, along with the body, can be described as follows:

  • Initialization Expression: This is where you initialize a loop counter variable with an initial value, which will be executed only once, at the beginning of the loop.
  • Condition Expression: This is where you define the condition that's evaluated before each iteration of the loop. If the condition evaluates to true, the loop continues; otherwise, it terminates.
  • Increment/Decrement Expression: This is where you update the loop counter variable at the end of each iteration. It can either increment or decrement the counter.
  • Body: This is the block of code that is executed repeatedly until the loop terminates.

Please note that the order in which the for loop executes is: 1) initialization expression, 2) condition expression, 3) body, and then 4) increment/decrement expression.

For example:

for ($i = 1; $i <= 5; $i++) {
    echo $i; // 1 2 3 4 5
}

In this example:

  • The loop counter variable "$i" is initialized to 1;
  • The condition "$i <= 5" is evaluated before each iteration;
  • The counter is incremented by 1 after each iteration;
  • The echo statement prints the value of "$i" until the loop terminates after the fifth iteration (i.e. when the value of "$i" is 6, which is greater than 5, and the condition "$i <= 5" evaluates to false).

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.