0
0
PHPprogramming~5 mins

For loop execution model in PHP

Choose your learning style9 modes available
Introduction

A for loop helps you repeat a set of actions many times without writing the same code again and again.

When you want to count from 1 to 10 and do something each time.
When you need to process each item in a list one by one.
When you want to repeat a task a fixed number of times, like printing a message 5 times.
When you want to run a loop with a clear start, end, and step.
Syntax
PHP
for (initialization; condition; increment) {
    // code to repeat
}

Initialization runs once at the start to set up the loop.

Condition is checked before each loop; if false, the loop stops.

Examples
This prints numbers 0 to 4, increasing $i by 1 each time.
PHP
<?php
for ($i = 0; $i < 5; $i++) {
    echo $i . "\n";
}
?>
This counts down from 10 to 1, decreasing $count by 1 each time.
PHP
<?php
for ($count = 10; $count > 0; $count--) {
    echo $count . "\n";
}
?>
This prints even numbers from 2 to 10, increasing by 2 each time.
PHP
<?php
for ($x = 2; $x <= 10; $x += 2) {
    echo $x . "\n";
}
?>
Sample Program

This program uses a for loop to print the word 'Number:' followed by numbers 1 through 5, each on a new line.

PHP
<?php
// Print numbers from 1 to 5
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i\n";
}
?>
OutputSuccess
Important Notes

The loop runs as long as the condition is true.

If the condition is false at the start, the loop body does not run at all.

You can change the increment to add or subtract any value, not just 1.

Summary

A for loop repeats code with a clear start, stop, and step.

It helps avoid writing the same code many times.

Initialization runs once, condition checks before each repeat, increment changes the loop variable.