Mastering the for Loop
Master the PHP for loop — initialization, condition, increment, nested loops, patterns, infinite loop pitfalls, and real-world examples.
Mastering the for Loop
Introduction
Imagine you need to display the numbers from 1 to 100.
Without loops, you would have to write:
echo 1;echo 2;echo 3;...echo 100;
This approach is slow, repetitive, and impossible to maintain.
Now imagine you need to send an email to 50,000 customers, process 10,000 database records, generate 365 daily reports, or display 100 products from a database.
Writing the same code repeatedly isn't practical.
This is why programming languages provide loops.
A loop allows PHP to execute the same block of code multiple times until a specified condition becomes false.
Loops are one of the most frequently used programming concepts. Every modern PHP application—whether it's Laravel, WordPress, Magento, CodeIgniter, or a custom enterprise application—relies heavily on loops.
In this lesson, you'll master the most commonly used loop in PHP: the for loop.
What is a Loop?
A loop is a programming construct that repeatedly executes a block of code while a condition remains true.
Instead of writing the same code multiple times, you write it once and let PHP repeat it automatically.
For example:
<?phpfor ($i = 1; $i <= 5; $i++) {echo "Hello PHP<br>";}
Output:
Hello PHP Hello PHP Hello PHP Hello PHP Hello PHP
The code inside the loop runs five times, even though it was written only once.
Why Are Loops Important?
Loops help you:
- Process large amounts of data.
- Display lists of products or users.
- Read database records.
- Validate form inputs.
- Generate reports.
- Create tables and calendars.
- Process files.
- Call APIs repeatedly.
- Automate repetitive tasks.
Without loops, many real-world applications would be impossible to build efficiently.
Types of Loops in PHP
PHP provides four main loop types:
| Loop | Best Used When |
|---|---|
| for | You know the number of iterations in advance. |
| while | You repeat until a condition becomes false. |
| do...while | The loop must execute at least once. |
| foreach | You iterate over arrays and collections. |
In this lesson, we'll focus on the for loop.
Understanding the for Loop
The for loop is ideal when you know how many times the loop should execute.
Syntax:
for (initialization; condition; increment) {// Code to execute}
It consists of three parts:
- Initialization
- Condition
- Increment (or decrement)
Let's understand each one.
Initialization
Initialization runs only once, before the loop starts.
Example:
$i = 1;
This creates a loop counter.
Think of it as the starting point.
Condition
Before every iteration, PHP checks the condition.
$i <= 5
If the condition is true: execute the loop.
If the condition is false: stop the loop.
Increment
After each iteration, PHP updates the counter.
$i++
This increases the value by one.
You can also decrease values using:
$i--
Complete Example
<?phpfor ($i = 1; $i <= 5; $i++) {echo $i . "<br>";}
Output:
1 2 3 4 5
Execution flow:
Iteration 1
$i = 1 Condition = true Print 1 Increment
Iteration 2
$i = 2 Condition = true Print 2 Increment
This continues until $i becomes 6.
Now:
6 <= 5
False. The loop ends.
Visualizing the for Loop
Start ↓ Initialize Counter ↓ Check Condition ↓ True? ↓ ↓ Yes No ↓ ↓ Execute End ↓ Increment ↓ Check Condition Again
This cycle repeats until the condition becomes false.
Printing Numbers
Example:
<?phpfor ($i = 1; $i <= 10; $i++) {echo $i . " ";}
Output:
1 2 3 4 5 6 7 8 9 10
Counting Backwards
You can also decrement.
<?phpfor ($i = 10; $i >= 1; $i--) {echo $i . " ";}
Output:
10 9 8 7 6 5 4 3 2 1
Incrementing by Different Values
The increment doesn't have to be one.
<?phpfor ($i = 0; $i <= 20; $i += 2) {echo $i . " ";}
Output:
0 2 4 6 8 10 12 14 16 18 20
Similarly:
$i += 5;
or
$i += 10;
Real-World Example: Display Product IDs
<?phpfor ($productId = 1001; $productId <= 1010; $productId++) {echo "Product ID: " . $productId . "<br>";}
Output:
Product ID: 1001 Product ID: 1002 ... Product ID: 1010
Real-World Example: Employee ID Cards
Imagine HR needs to generate ID cards for employees numbered 1 to 50.
<?phpfor ($employee = 1; $employee <= 50; $employee++) {echo "Generating ID Card for Employee #" . $employee . "<br>";}
Instead of writing 50 statements, a single loop completes the task.
Real-World Example: Email Campaign
<?php$totalEmails = 5;for ($i = 1; $i <= $totalEmails; $i++) {echo "Sending Email " . $i . "<br>";}
Output:
Sending Email 1 Sending Email 2 Sending Email 3 Sending Email 4 Sending Email 5
Enterprise applications often process thousands of records in a similar way.
Nested for Loops
A loop can contain another loop.
Example:
<?phpfor ($row = 1; $row <= 3; $row++) {for ($column = 1; $column <= 3; $column++) {echo "(" . $row . "," . $column . ") ";}echo "<br>";}
Output:
(1,1) (1,2) (1,3) (2,1) (2,2) (2,3) (3,1) (3,2) (3,3)
Nested loops are useful for:
- Tables
- Matrices
- Seating arrangements
- Chess boards
- Calendar generation
Multiplication Table
<?phpfor ($i = 1; $i <= 10; $i++) {echo "5 × " . $i . " = " . (5 * $i) . "<br>";}
Output:
5 × 1 = 5 ... 5 × 10 = 50
Creating Patterns
Example:
<?phpfor ($i = 1; $i <= 5; $i++) {for ($j = 1; $j <= $i; $j++) {echo "*";}echo "<br>";}
Output:
* ** *** **** *****
Pattern-based questions are common in coding interviews because they test your understanding of loops and nested logic.
Infinite Loops
Be careful. This loop never ends.
<?phpfor (;;) {echo "Running...";}
Or:
<?phpfor ($i = 1; $i <= 5;) {echo $i;}
Since $i never changes, the condition always remains true.
Infinite loops can consume CPU and memory, making your application unresponsive. Always ensure that the loop condition eventually becomes false.
Performance Considerations
Loops are efficient, but unnecessary work inside a loop can slow your application.
Instead of:
<?phpfor ($i = 0; $i < count($products); $i++) {// Process product}
A better approach is:
<?php$totalProducts = count($products);for ($i = 0; $i < $totalProducts; $i++) {// Process product}
By storing the count once, PHP doesn't need to calculate it during every iteration.
While modern PHP versions optimize many cases, caching values that are expensive to compute is still a useful habit when performance matters.
Best Practices
Use Meaningful Variable Names
Instead of:
for ($x = 1; $x <= 10; $x++)
Use:
for ($studentNumber = 1; $studentNumber <= 10; $studentNumber++)
Use short names like $i or $j only for simple, local loop counters.
Keep Loops Focused
A loop should perform one primary task.
If it grows too complex, move parts of the logic into helper functions.
Avoid Deep Nesting
Multiple nested loops make code difficult to read and can affect performance.
Whenever possible, simplify the logic.
Prefer Readability
Write loops that other developers can understand at a glance.
Readable code is easier to maintain than clever code.
Common Mistakes
Off-by-One Errors
Incorrect:
for ($i = 1; $i < 10; $i++)
This prints only 1 through 9.
If you intended to include 10, use:
for ($i = 1; $i <= 10; $i++)
Forgetting to Update the Counter
for ($i = 1; $i <= 5;) {echo $i;}
This creates an infinite loop because $i never changes.
Modifying the Loop Counter Unnecessarily
for ($i = 1; $i <= 10; $i++) {if ($i == 5) {$i = 9;}echo $i;}
Changing the loop counter inside the loop makes the code harder to understand and can introduce subtle bugs.
Doing Heavy Work in Every Iteration
Avoid repeating expensive operations such as database queries or complex calculations inside loops when the result can be computed once before the loop.
Hands-on Exercise
Create a PHP script that:
- Prints numbers from 1 to 100.
- Prints numbers from 100 to 1.
- Displays only even numbers from 2 to 50.
- Generates the multiplication table for the number 8.
- Prints a triangle pattern using nested loops.
- Generates employee IDs from EMP1001 to EMP1020.
- Counts down from 10 and prints "Liftoff!" at the end.
- Identify and fix an intentionally created infinite loop.
Try solving these exercises before looking for solutions. Writing the code yourself is the fastest way to build confidence.
Summary
The for loop is one of the most powerful and widely used looping constructs in PHP.
It is best suited for situations where you know in advance how many times a task needs to be repeated.
In this lesson, you learned how a for loop works, how initialization, conditions, and increments interact, how to create nested loops, generate patterns, avoid infinite loops, and write clean, maintainable looping logic.
A solid understanding of the for loop will make it much easier to work with arrays, databases, files, APIs, and other real-world programming tasks.
Key Takeaways
- A loop repeats a block of code automatically.
- The
forloop is ideal when the number of iterations is known. - Every
forloop has initialization, a condition, and an increment or decrement. - Nested loops are useful for working with tables, matrices, and patterns.
- Always ensure your loop has a valid exit condition.
- Keep loops simple, readable, and focused on one responsibility.
- Avoid unnecessary work inside loops for better performance.
- Practice writing loops regularly—they are one of the most important building blocks in PHP programming.
What's Next?
In Mastering while and do...while Loops, you'll learn while and do...while — ideal when the number of iterations is unknown, such as reading database records, files, and user prompts.
Continue at /learn/php/loops-part-2.