PHP For Loop: Run Code Using a Counter with Examples

for loop in php

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.

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:

  1. Initialization: Sets the start value ($i = 1)
  2. Condition Check: Tests if the loop should continue ($i <= 5)
  3. Execution: Runs the code block
  4. Update: Increments or decrements the counter ($i++)
  5. Repeat: Checks the condition again
  6. 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:

FeatureFor LoopForeach Loop
Use caseCounting, ranges, indexed arraysArrays and objects
Index handlingManual ($i)Automatic
SyntaxMore setup (init, condition, increment)Simple (foreach ($array as $value))
ReadabilityCan be harder to read with arraysVery clear for arrays
FlexibilityWorks with any counting logicOnly 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?

It repeats code a set number of times. You use it for counting, processing arrays, or building output.

How do I stop a for loop?

You use break to exit early when a condition matches.

Can I skip steps in a for loop?

Yes. You use continue to jump to the next iteration without running the remaining code.

What is the difference between for and foreach?

For uses indexes and works for numeric ranges or arrays. Foreach steps through arrays without indexes.

How can I create HTML with a for loop?

You write HTML tags inside the loop body. PHP prints each piece as the loop runs.
Previous Article

JavaScript Math tan: The Tangent of an Angle in Radians

Next Article

JavaScript Math asin: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.