The for
loop in PHP is used when you know exactly how many times you want to execute a block of code. It consists of three parts:
- Initialization: Set a loop counter.
- Condition: Defines when the loop should stop.
- Increment/Decrement: Updates the counter in each iteration.
Syntax of a PHP For Loop
<?php for (initialization; condition; increment/decrement) { // Code to be executed } ?>
📝 Example 1: Simple For Loop
Prints numbers from 1 to 5.
<?php for ($i = 1; $i <= 5; $i++) { echo "Number: $i <br>"; } ?>
📝 Example 2: For Loop with Decrement
Prints numbers from 5 to 1.
<?php for ($i = 5; $i >= 1; $i--) { echo "Countdown: $i <br>"; } ?>
📝 Example 3: For Loop with Step
Counts from 0 to 10 in steps of 2.
<?php for ($i = 0; $i <= 10; $i += 2) { echo "Step: $i <br>"; } ?>
🎯 When to Use a For Loop?
- When you know the number of iterations in advance.
- For iterating over a range of numbers with a fixed step.
- When updating an index variable systematically.
📝 Practice Time!
Modify the examples above and experiment with different values to understand how for loops work.