PHP for Loop : A Tutorial with Examples

In PHP, the for loop is a fundamental control structure used for executing a block of code a set number of times. It is most commonly used when the number of iterations is known beforehand.

The for loop provides a more compact structure compared to the while loop and is especially useful for iterating over arrays, performing repetitive tasks, and controlling iterations in a simple manner.

In this tutorial, we will cover:

Let’s explore each of these concepts with examples and explanations.

1. What is a for Loop?

A for loop in PHP is a control structure that allows you to repeatedly execute a block of code a specified number of times. It is ideal when the number of iterations is known in advance. The for loop is more compact than a while loop because it combines the loop’s initialization, condition check, and increment/decrement in a single line.

2. Basic Syntax of for Loop

The for loop consists of three parts inside parentheses:

  1. Initialization: This is executed once at the beginning of the loop.
  2. Condition: The loop runs as long as this condition evaluates to true.
  3. Increment/Decrement: This is executed after each iteration to update the loop counter.

Syntax:

for (initialization; condition; increment) {
    // Code to execute on each iteration
}
  • initialization: Sets the starting value of the loop counter (e.g., $i = 0).
  • condition: The loop runs as long as this condition is true.
  • increment/decrement: This is executed after each iteration to update the loop counter.

3. How the for Loop Works

  1. Initialization: The loop counter is initialized (e.g., $i = 0).
  2. Condition: Before each iteration, PHP checks whether the condition is true.
  3. Execution: If the condition is true, the code block inside the loop is executed.
  4. Increment/Decrement: After the code block is executed, the loop counter is updated (e.g., $i++).
  5. Repeat: The process repeats until the condition evaluates to false.

4. Examples of Using the for Loop

Example 1: Basic for Loop

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Iteration: $i\n";
}
?>

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
  • In this example, the loop initializes $i = 1 and continues as long as $i <= 5. After each iteration, $i is incremented by 1 ($i++).

Example 2: Decrementing in a for Loop

<?php
for ($i = 5; $i >= 1; $i--) {
    echo "Countdown: $i\n";
}
?>

Output:

Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
  • In this example, the loop starts with $i = 5 and decrements ($i–) after each iteration, running until $i is no longer greater than or equal to 1.

Example 3: Iterating Over an Array

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

for ($i = 0; $i < count($fruits); $i++) {
    echo "Fruit: $fruits[$i]\n";
}
?>

Output:

Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date
  • In this example, the loop iterates over an array of fruits. The count($fruits) function is used to determine the length of the array, and the loop runs until the end of the array.

5. Using break and continue in for Loops

break Statement:

The break statement is used to exit the loop early, regardless of the loop condition.

Example (Using break in a for Loop):

<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 6) {
        break;  // Exit the loop when $i equals 6
    }
    echo "Iteration: $i\n";
}
?>

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
  • In this example, the loop is terminated early when $i equals 6, even though the condition would allow it to run until 10.

continue Statement:

The continue statement skips the remaining code in the current iteration and moves to the next iteration.

Example (Using continue in a for Loop):

<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) {
        continue;  // Skip iteration when $i equals 3
    }
    echo "Iteration: $i\n";
}
?>

Output:

Iteration: 1
Iteration: 2
Iteration: 4
Iteration: 5
  • In this example, the continue statement skips the iteration when $i equals 3. The loop continues with the next value of $i.

6. Nested for Loops

A nested for loop is a for loop inside another for loop. Nested loops are useful for iterating over multidimensional data structures, such as 2D arrays.

Example (Nested for Loop):

<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        echo "i = $i, j = $j\n";
    }
}
?>

Output:

i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2
i = 3, j = 1
i = 3, j = 2
  • In this example, the outer loop ($i) iterates three times, and for each iteration of the outer loop, the inner loop ($j) iterates twice.

7. Difference Between for and while Loops

Both for and while loops can be used to repeat a block of code multiple times, but they have different use cases:

for Loop:

  • Best used when: You know the number of iterations beforehand.
  • Syntax: Combines initialization, condition, and increment/decrement in a single line.
  • Use case: Iterating over arrays, performing repetitive tasks a fixed number of times.

while Loop:

  • Best used when: You do not know the number of iterations in advance and need the loop to run until a certain condition is met.
  • Syntax: Initialization, condition, and increment/decrement are handled separately.
  • Use case: Running a loop until a dynamic condition is met.

Example (for vs while):

<?php
// For loop (fixed number of iterations)
for ($i = 1; $i <= 3; $i++) {
    echo "For loop iteration: $i\n";
}

// While loop (condition-based)
$i = 1;
while ($i <= 3) {
    echo "While loop iteration: $i\n";
    $i++;
}
?>

8. Common Use Cases for for Loop

The for loop is commonly used in the following scenarios:

  • Iterating over arrays: Looping through each element of an array.
  • Performing repetitive tasks: When you need to execute a block of code a known number of times.
  • Generating sequences: Creating number sequences or patterns.
  • Nested loops: Working with multidimensional arrays or grids.

Example: Generating a Multiplication Table

<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= 5; $j++) {
        echo $i * $j . "\t";
    }
    echo "\n";
}
?>

Output:

1   2   3   4   5   
2   4  

 6   8   10  
3   6   9   12  15  
4   8   12  16  20  
5   10  15  20  25  
  • In this example, a nested for loop is used to generate a multiplication table for numbers 1 through 5.

Summary of PHP for Loop:

Concept Description
Basic Syntax Combines initialization, condition, and increment in one line.
Condition Checked Each Iteration The condition is evaluated before each iteration to control the loop.
Using break Exits the loop early, even if the condition has not been met.
Using continue Skips the current iteration and proceeds to the next one.
Nested for Loops A for loop inside another for loop, often used for multidimensional arrays.
Difference from while Loop for loops are typically used when the number of iterations is known in advance.

Conclusion

The for loop in PHP is a versatile and powerful control structure for repetitive tasks, especially when the number of iterations is known.

In this tutorial, we covered:

  • The syntax of the for loop and how it works.
  • Several examples to illustrate different use cases of the for loop, including array iteration and nested loops.
  • The use of break and continue to control the flow of the loop.
  • The difference between for and while loops and when to use each.

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples