You may need to repeat tasks in PHP. The PHP for loop solves this by letting you run code many times without writing it over and over. It provides control over starting point, condition, and steps.
Table of Content
- Understand the “for” Loop in PHP
- Use the “for” Loop to Decrement Backward in PHP
- Use the “for” Loop with Arrays
- Skip Iterations with Continue in “for” Loop
- Break Out of “for” Loops
- Combine the “for” Loop with If Statements
- The Difference Between “for” Loop and “foreach” Loop in PHP
- Generate HTML with the “for” Loop
- Examples of “for” Loop in PHP
- Wrapping Up
- FAQs
Understand the “for” Loop in PHP
A for loop is a control structure in PHP that repeats code a set number of times. You define where to start, when to stop, and how to move to the next step.
Here is the syntax:
for (start; condition; change) {
// code to run
}- Start sets the first value.
- Condition checks if PHP should run the block.
- Change updates the value each time.
A for loop in PHP lets you run a block of code many times. You set it up with three parts: start value, condition, and change. PHP checks the condition before each run.
If the condition is true, PHP runs the block. Then it updates the value and checks again.
But, how does a for loop work?
Here’s how it runs step by step:
- Initialization: Sets the start value (
$i = 1) - Condition Check: Tests if the loop should continue (
$i <= 5) - Execution: Runs the code block
- Update: Increments or decrements the counter (
$i++) - Repeat: Checks the condition again
- If the condition becomes false, the loop stops.
Here is a quick example:
for ($i = 0; $i < 5; $i++) {
echo $i . " ";
}- Start:
$i = 0 - Condition:
$i < 5 - Change:
$i++
This starts at 0 and stops before 5. It prints 0 1 2 3 4. You use this pattern to repeat code with precise control, such as listing items or processing data in steps.
So, why choose a for loop in PHP?
Because you want to repeat actions a known number of times while controlling each step. It saves time, reduces errors, and makes your code clear and easy to change.
If you forget the condition or always make it true, the loop runs forever.
for (;;) {
echo "Infinite";
}This loop never stops. Always set a clear condition to avoid freezing your program.
Use the “for” Loop to Decrement Backward in PHP
Here you use for loop to count backward by reducing the counter value each time.
Countdown numbers:
for ($i = 5; $i >= 1; $i--) {
echo $i . " ";
}Here is the output:
5 4 3 2 1
This loop starts at 5. It runs while $i is at least 1. After each run, it subtracts 1. You see the numbers printed in reverse order.
Even numbers in reverse:
for ($i = 10; $i >= 2; $i -= 2) {
echo "Even: $i\n";
}Output:
Even: 10
Even: 8
Even: 6
Even: 4
Even: 2
This loop starts at 10 and subtracts 2 each time. It stops when $i is less than 2. You get all even numbers down to 2.
Use the “for” Loop with Arrays
A for loop works well for indexed arrays. You use the array length to set limits and access each item by index.
For example:
$colors = ["Red", "Green", "Blue"];
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i] . "\n";
}Here is the output:
Red
Green
Blue
This loop starts at 0. It stops before reaching the array length. It prints each element in order.
Here is another example to list numbers:
$fruits = ["Apple", "Banana", "Cherry"];
for ($i = 0; $i < count($fruits); $i++) {
echo ($i + 1) . ". " . $fruits[$i] . "\n";
}Output:
1. Apple
2. Banana
3. Cherry
The loop numbers each item by adding 1 to the index. You get a neat list.
Skip Iterations with Continue in “for” Loop
Sometimes you must skip certain steps in the loop. You use the continue statement to jump to the next iteration. PHP ignores the remaining code for that cycle.
For example:
for ($i = 1; $i <= 5; $i++) {
if ($i % 2 != 0) {
continue;
}
echo "Even: $i\n";
}Here is the output:
Even: 2
Even: 4
This loop checks if the number is odd. If so, it skips printing. Only even numbers appear.
Here is another example to skip number 3:
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo "Number: $i\n";
}Output:
Number: 1
Number: 2
Number: 4
Number: 5
The loop skips 3 and prints all other numbers.
Break Out of “for” Loops
If you want to exit a loop early, you use break. Once PHP reaches break, it stops running the loop immediately.
Here is an example of break and echo together in a for loop:
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
break;
}
echo "Count: $i\n";
}Output:
Count: 1
Count: 2
PHP ends the loop when $i equals 3.
Combine the “for” Loop with If Statements
You often mix if with for to add conditions. This allows you to filter items, stop loops, or change behavior.
For example:
for ($i = 1; $i <= 4; $i++) {
if ($i > 2) {
echo "Large: $i\n";
}
}Output:
Large: 3
Large: 4
This loop counts from 1 to 4. It prints “Large: number” for each number greater than 2 (so it outputs for 3 and 4).
The Difference Between “for” Loop and “foreach” Loop in PHP
The for loop uses indexes and works with numeric ranges. You need to track the counter yourself. The foreach loop steps through arrays automatically, assigning each item to a variable.
Here is a table shows you keys differences:
| Feature | For Loop | Foreach Loop |
|---|---|---|
| Use case | Counting, ranges, indexed arrays | Arrays and objects |
| Index handling | Manual ($i) | Automatic |
| Syntax | More setup (init, condition, increment) | Simple (foreach ($array as $value)) |
| Readability | Can be harder to read with arrays | Very clear for arrays |
| Flexibility | Works with any counting logic | Only works with arrays and objects |
So, For loop:
- Best for numeric ranges or when you need to control the index.
- You must set up a counter (
$i) and update it yourself. - You can use it with arrays, but you must manage indexes manually.
But, foreach:
- Designed for arrays and objects.
- It automatically moves through each element, and the element is assigned to a variable on each iteration.
- It assigns the current item to a variable without using indexes.
- Easier to read and less error-prone when working with collections.
Generate HTML with the “for” Loop
A for loop can produce repeated HTML. You build table rows, lists, or other elements dynamically.
Here is an example for create list items:
for ($i = 1; $i <= 3; $i++) {
echo "<li>Item $i</li>";
}Output:
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
This loop runs 3 times, counting from 1 to 3. It prints an HTML list item for each number (like <li>Item 1</li>).
Examples of “for” Loop in PHP
Multiply by 2
for ($i = 1; $i <= 3; $i++) {
echo $i * 2 . "\n";
}This loop counts from 1 to 3. It prints each number multiplied by 2 (2, 4, and 6).
Loop Backward:
for ($i = 3; $i >= 1; $i--) {
echo "Step $i\n";
}This loop counts backward from 3 to 1. It prints “Step” with each number (Step 3, Step 2, Step 1).
Skip 2:
for ($i = 1; $i <= 3; $i++) {
if ($i == 2) continue;
echo "$i\n";
}This loop counts from 1 to 3. It skips 2 and prints only 1 and 3.
Break at 2:
for ($i = 1; $i <= 3; $i++) {
if ($i == 2) break;
echo "$i\n";
}This loop starts counting from 1. It stops completely when $i is 2, so it only prints 1.
Wrapping Up
In this article, you learned how the for loop works and how you can use it to repeat tasks, work with arrays, and control output. Here is a quick recap:
- For loops help you generate HTML or process arrays.
- A for loop repeats code while a condition stays true.
- You define a start point, a test, and an update step.
- You can decrement, skip steps, or break out of the statement early.
FAQs
What is a for loop used for?
How do I stop a for loop?
Can I skip steps in a for loop?
What is the difference between for and foreach?
How can I create HTML with a for loop?
Similar Reads
Today, we will discuss the most prominent and useful superglobal in PHP, $_REQUEST, to get user input. The $_REQUEST array lets you retrieve…
PHP Variadic functions show you a way to handle a variable number of arguments within a function. They are designed…
PHP namespace solves the problem of name conflicts. Different developers may create functions-classes, or constants with the same name. PHP…
You use PHP every day if you build websites, but most people do not know where it came from or…
Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters,…
The array_key_last gives you the last key in an array and works with numeric and associative arrays in PHP. It…
The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…
One of the important tasks is retrieving documents from a collection. MongoDB help us to make this process, but understanding…
Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…
The PHP associative array is a structured collection wherein data elements are organized into lists or groups. Each element is…