PHP Programming

PHP For Loops

What is a for Loop?

A for loop in PHP (and many other programming languages) is used when you know exactly how many times you want to repeat a block of code. It has a clear start, end, and increment or decrement.

Syntax of a for Loop


for (initialization; condition; increment/decrement) 
    {
    // Code to be executed repeatedly
    }
  • Initialization: This happens once at the start of the loop. It typically sets a counter.
  • Condition: As long as this condition is true, the loop keeps running.
  • Increment/Decrement: Changes the counter after each iteration (increases or decreases).

Simple Example: Counting from 1 to 5

This example demonstrates counting from 1 to 5 using a for loop.


for ($i = 1; $i <= 5; $i++) 
    {
    echo "Number: $i<br>";
    }

Explanation:

  • Start with $i = 1.
  • As long as $i <= 5, it prints the value.
  • After printing, $i is incremented by 1 ($i++).
  • The process repeats until $i becomes greater than 5.

Output:


Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example: Printing Even Numbers between 1 and 10


for ($i = 2; $i <= 10; $i += 2) 
    {
    echo "Even number: $i<br>";
    }

Explanation:

  • Starts with $i = 2.
  • As long as $i <= 10, it prints the value.
  • Instead of increasing by 1, it increases by 2 ($i += 2).

Output:


Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10

Example: Looping Backwards from 10 to 1


for ($i = 10; $i >= 1; $i--) 
    {
    echo "Countdown: $i<br>";
    }

Explanation:

  • Starts with $i = 10.
  • Runs as long as $i >= 1.
  • Decreases $i by 1 each time ($i--).

Output:


Countdown: 10
Countdown: 9
Countdown: 8
Countdown: 7
Countdown: 6
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

Example: Using a for Loop with Arrays


$colors = ["Red", "Green", "Blue", "Yellow"];

for ($i = 0; $i < count($colors); $i++) 
    {
    echo "Color: $colors[$i]<br>";
    }

Explanation:

  • Starts with $i = 0.
  • Runs until $i is less than the length of the array.
  • Accesses each element using $colors[$i].

Output:


Color: Red
Color: Green
Color: Blue
Color: Yellow

Example: Nested for Loop (Multiplication Table)


for ($i = 1; $i <= 3; $i++) 
    {
    for ($j = 1; $j <= 3; $j++) 
        {
        echo "$i x $j = " . ($i * $j) . "<br>";
        }
    echo "<br>";
    }

Explanation:

  • The outer loop controls the first number.
  • The inner loop multiplies the first number with the second number.
  • This prints a small multiplication table.

Output:


1 x 1 = 1
1 x 2 = 2
1 x 3 = 3

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
To top