Web Analytics

PHP For Loops

Beginner~25 min read

The for loop is perfect when you know exactly how many times you need to iterate. With initialization, condition, and increment all in one place, it's the cleanest way to write counted loops.

For Loop Syntax

A for loop has three expressions in its header:

<?php
for (initialization; condition; increment) {
    // Code to repeat
}
?>
Part Purpose Example
Initialization Set up loop variable (runs once) $i = 0
Condition Check before each iteration $i < 10
Increment Update after each iteration $i++
Output
Click Run to execute your code

Loop Execution Flow

Here's exactly what happens when a for loop runs:

<?php
// for ($i = 1; $i <= 3; $i++)

// Step 1: $i = 1 (initialization - runs once)
// Step 2: Is $i <= 3? (1 <= 3? Yes!) โ†’ Execute body โ†’ Print "1"
// Step 3: $i++ ($i becomes 2)
// Step 4: Is $i <= 3? (2 <= 3? Yes!) โ†’ Execute body โ†’ Print "2"
// Step 5: $i++ ($i becomes 3)
// Step 6: Is $i <= 3? (3 <= 3? Yes!) โ†’ Execute body โ†’ Print "3"
// Step 7: $i++ ($i becomes 4)
// Step 8: Is $i <= 3? (4 <= 3? No!) โ†’ Exit loop

for ($i = 1; $i <= 3; $i++) {
    echo $i . "\n";
}
// Output: 1, 2, 3
?>

Common Patterns

Counting Up (most common)

<?php
// Count from 1 to 10
for ($i = 1; $i <= 10; $i++) {
    echo "$i ";
}
// Output: 1 2 3 4 5 6 7 8 9 10
?>

Counting Down

<?php
// Count from 10 to 1
for ($i = 10; $i >= 1; $i--) {
    echo "$i ";
}
// Output: 10 9 8 7 6 5 4 3 2 1
?>

Custom Step Values

<?php
// Step by 2 (even numbers)
for ($i = 0; $i <= 10; $i += 2) {
    echo "$i ";
}
// Output: 0 2 4 6 8 10

// Step by 5
for ($i = 0; $i <= 100; $i += 5) {
    echo "$i ";
}
// Output: 0 5 10 15 ... 95 100
?>
Array Iteration: When iterating arrays, use $i < count($array) (not <=) since array indices start at 0. Better yet, use foreach for arrays!

Iterating Arrays with For

<?php
$fruits = ["Apple", "Banana", "Cherry", "Date"];

// Traditional for loop with array
for ($i = 0; $i < count($fruits); $i++) {
    echo ($i + 1) . ". " . $fruits[$i] . "\n";
}

// Output:
// 1. Apple
// 2. Banana
// 3. Cherry
// 4. Date

// Optimization: Cache count() outside loop
$length = count($fruits);
for ($i = 0; $i < $length; $i++) {
    // ...
}
?>
Performance Tip: Store count($array) in a variable before the loop. Otherwise, PHP recalculates it on every iteration.

Nested For Loops

Place one loop inside another for multi-dimensional iterations:

Output
Click Run to execute your code

Multiple Variables

You can use multiple variables in a for loop:

<?php
// Two counters moving in opposite directions
for ($left = 0, $right = 4; $left < $right; $left++, $right--) {
    echo "left: $left, right: $right\n";
}
// Output:
// left: 0, right: 4
// left: 1, right: 3

// Parallel arrays
$names = ["Alice", "Bob", "Carol"];
$ages = [25, 30, 28];
$len = count($names);

for ($i = 0; $i < $len; $i++) {
    echo "{$names[$i]} is {$ages[$i]} years old.\n";
}
?>

Optional Expressions

All three expressions in a for loop are optional:

<?php
// External initialization
$i = 0;
for (; $i < 5; $i++) {
    echo $i;
}

// External increment
for ($i = 0; $i < 5;) {
    echo $i;
    $i++;
}

// Infinite loop (use break to exit)
for (;;) {
    // Must use break or return to exit!
    break;
}
?>

Alternative Syntax

For use in templates:

<?php $items = ["Home", "About", "Contact"]; ?>

<ul>
<?php for ($i = 0; $i < count($items); $i++): ?>
    <li><?= $items[$i] ?></li>
<?php endfor; ?>
</ul>

Common Mistakes

1. Off-by-one errors with arrays

<?php
$arr = [1, 2, 3, 4, 5];  // Indices: 0, 1, 2, 3, 4

// โŒ WRONG: <= includes index 5 which doesn't exist
for ($i = 0; $i <= count($arr); $i++) {
    echo $arr[$i];  // Error on last iteration!
}

// โœ… CORRECT: Use < for zero-indexed arrays
for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i];
}
?>

2. Modifying loop variable incorrectly

<?php
// โŒ WRONG: Unpredictable behavior
for ($i = 0; $i < 10; $i++) {
    if ($i === 5) {
        $i = 8;  // Don't modify inside loop!
    }
    echo $i;
}

// โœ… CORRECT: Use continue or break instead
for ($i = 0; $i < 10; $i++) {
    if ($i === 5) {
        continue;  // Skip this iteration
    }
    echo $i;
}
?>

3. Calling count() in condition

<?php
$bigArray = range(1, 10000);

// โŒ SLOW: count() called 10,000 times
for ($i = 0; $i < count($bigArray); $i++) {
    // ...
}

// โœ… FAST: count() called once
$length = count($bigArray);
for ($i = 0; $i < $length; $i++) {
    // ...
}
?>
When to Use For vs Foreach:
  • Use for when you need the index or specific iteration count
  • Use foreach when you just need to iterate all elements (next lesson!)
  • Use while when iterations depend on runtime conditions

Exercise: Pattern Generator

Task: Create a diamond pattern using nested for loops.

Requirements:

  • Accept a size parameter (e.g., 5)
  • Print a diamond shape using asterisks
  • Center each row properly with spaces
Show Solution
<?php
$size = 5;

// Upper half (including middle)
for ($i = 1; $i <= $size; $i++) {
    // Print spaces
    for ($s = $size - $i; $s > 0; $s--) {
        echo " ";
    }
    // Print stars
    for ($j = 1; $j <= (2 * $i - 1); $j++) {
        echo "*";
    }
    echo "\n";
}

// Lower half
for ($i = $size - 1; $i >= 1; $i--) {
    // Print spaces
    for ($s = $size - $i; $s > 0; $s--) {
        echo " ";
    }
    // Print stars
    for ($j = 1; $j <= (2 * $i - 1); $j++) {
        echo "*";
    }
    echo "\n";
}

/* Output (size=5):
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
*/
?>

Summary

  • Syntax: for (init; condition; increment)
  • Initialization: Runs once before the loop starts
  • Condition: Checked before each iteration
  • Increment: Runs after each iteration
  • Count up: $i++ or $i += step
  • Count down: $i-- or $i -= step
  • Nested loops: Use different variables ($i, $j, $k)
  • Arrays: Use < count(), not <=

What's Next?

For loops are great for indexed access, but PHP has an even better way to iterate arrays. Let's explore Foreach Loops - designed specifically for arrays and objects!