Friday, June 12, 2026
HomeLanguagesPHP for Loop

PHP for Loop

The for loop is the most complex loop in PHP that is used when the user knows how many times the block needs to be executed. The for loop contains the initialization expression, test condition, and update expression (expression for increment or decrement).

Flowchart of for Loop:

 

Syntax:

for (initialization expression; test condition; update expression) {
   // Code to be executed
}

Loop Parameters:

  • Initialization Expression: In this expression, we have to initialize the loop counter to some value. For example: $num = 1;
  • Test Condition: In this expression, we have to test the condition. If the condition evaluates to “true” then it will execute the body of the loop and go to the update expression otherwise it will exit from the for loop. For example: $num <= 10;
  • Update Expression: After executing the loop body, this expression increments/decrements the loop variable by some value. For example: $num += 2;

Example 1: The following code shows a simple example using for loop.

PHP




<?php
  
    // for Loop to display numbers
    for( $num = 0; $num < 20; $num += 5) {
        echo $num . "\n";
    }
  
?>


Output

0
5
10
15

Example 2: The following code shows another example of for loop.

PHP




<?php
  
    // for Loop to display numbers
    for( $num = 1; $num < 50; $num++) 
    {
        if($num % 5 == 0)
            echo $num . "\n";
    }
?>


Output

5
10
15
20
25
30
35
40
45

Reference: https://www.php.net/manual/en/control-structures.for.php

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS