Google News
logo
PHP Program to for loop
The `for` loop is a type of loop statement in PHP that allows you to execute a block of code repeatedly for a specified number of times.

The basic syntax of a `for` loop in PHP is as follows :
for (initialization; condition; increment/decrement) {
    // code to execute for each iteration
}​
In this syntax, `initialization` is an expression that is executed once before the loop starts, `condition` is an expression that is evaluated before each iteration of the loop, and `increment/decrement` is an expression that is executed after each iteration of the loop.

If `condition` is true, then the code inside the loop is executed. After the code inside the loop is executed, the `increment/decrement` expression is executed, and the loop continues as long as `condition` is true.

Here's an example of a PHP program that uses a `for` loop to print the numbers from 1 to 10 :
Program :
<?php
    // This is a PHP program that uses a for loop to print the numbers from 1 to 10
    
    for ($i = 1; $i <= 10; $i++) {
        echo $i . " ";
    }
?>
Output :
1 2 3 4 5 6 7 8 9 10
In this code, the `for` loop initializes the variable `$i` to `1`, checks if `$i` is less than or equal to `10`, and increments `$i` by `1` after each iteration. The code inside the loop simply prints the value of `$i`, followed by a space.

After the first iteration of the loop, `$i` is incremented to `2`, and the condition is checked again. This process repeats until `$i` reaches `11`, at which point the condition is no longer true, and the `for` loop exits.

This demonstrates how `for` loops can be used to execute a block of code repeatedly for a specified number of times.