PHP : for Loop

In PHP, the for loop is a control structure that allows you to execute a block of code a specified number of times. It's often used when you know in advance how many times you want to execute a block of code.

Here's the basic syntax of a `for` loop:


for (initialization; condition; increment/decrement) {
    // code to be executed
}
 

Here's how it works:

1. initialization: This part initializes the loop control variable. It is executed once, as the loop begins.
2. condition: This part specifies the condition for continuing the loop. If the condition evaluates to true, the loop continues; if it evaluates to false, the loop stops.
3. increment/decrement: This part updates the loop control variable after each iteration. It can be an increment (e.g., i++) or decrement (e.g., i--).

Here's an example to illustrate how a for loop works:


<?php
for ($i = 1; $i <= 5; $i++) {
    echo "The value of i is: $i <br>";
}
?>

 

This loop will output:


The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5

 

In this example:

  • initialization: $i = 1 initializes the loop control variable $i to 1.
  • condition: $i <= 5 specifies that the loop should continue as long as $i is less than or equal to 5.
  • increment: $i++ increments the value of $i by 1 in each iteration.