Learn with Yasir

Share Your Feedback

PHP for Loop Tutorial with Syntax and Examples


Master the for loop in PHP to execute code repeatedly with control. Explore syntax, practical examples, and best practices for efficient PHP programming.

πŸ” for Statement in PHP

The for loop is one of the most commonly used loops in PHP. It lets you repeat a block of code a certain number of times. If you’ve used for loops in languages like C or JavaScript, PHP’s version will feel familiar.


πŸ“Œ Syntax

for (initialization; condition; increment) {
    // Code to be repeated
}

🧩 Explanation:

  • initialization – This runs once at the beginning. It’s usually used to set up a counter variable.
  • condition – This is checked before every loop. If it’s true, the loop runs again. If it’s false, the loop stops.
  • increment – This runs at the end of every loop iteration, usually to update the counter.

πŸ’‘ All three parts are optional, but at least the semicolons (;) must be there.


βœ… Simple Example

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i <br>";
}
?>

Output:

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

πŸ”„ More Examples

Example 1 – Classic for loop

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

Example 2 – No condition in the for loop

for ($i = 1; ; $i++) {
    if ($i > 10) {
        break; // Stop the loop manually
    }
    echo $i;
}

Example 3 – All parts inside the loop

$i = 1;
for (; ; ) {
    if ($i > 10) break;
    echo $i;
    $i++;
}

🌐 Example in an HTML Page

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP For Loop</title>
</head>
<body>

<?php
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
}
?>

</body>
</html>

πŸ“ Summary

  • Use for loops when you know exactly how many times you want to run a block of code.
  • You can skip any part of the loop structure, but be careful to avoid infinite loops.
  • The loop ends when the condition becomes false.

further reading:


🧠 Practice & Progress

Explore More Topics

PHP Basics

More ...