Loops in PHP
Loops allow PHP to execute a block of code repeatedly, either a set number of times or until a certain condition is met. They help make your code efficient and reduce repetition.
🧠 Why Use Loops?
- Repeat tasks multiple times
- Iterate through data like arrays
- Reduce code duplication
🔁 1. For Loop
Best when you know how many times you want the loop to run.
for ($i = 1; $i <= 5; $i++) { echo "Line $i<br>"; }
Output:
- Line 1
- Line 2
- Line 3
- Line 4
- Line 5
🔄 2. While Loop
Executes code as long as the condition is true.
$i = 1; while ($i <= 5) { echo "Count: $i<br>"; $i++; }
🔁 3. Do...While Loop
This loop runs at least once, even if the condition is false.
$i = 1; do { echo "Number: $i<br>"; $i++; } while ($i <= 5);
📦 4. Foreach Loop
Specifically used for iterating over arrays.
$fruits = ["apple", "banana", "orange"]; foreach ($fruits as $fruit) { echo "$fruit<br>"; }
Output:
- apple
- banana
- orange
🧾 Summary Table
Loop Type | Use Case | Condition Check Location |
---|---|---|
for | Known number of repetitions | Before loop starts (top) |
while | Unknown repetitions, condition checked first | Top |
do...while | Always run once, then check | Bottom |
foreach | Loop through arrays | Internally handled |
💡 Best Practices:
- Use
for
for counting and fixed loops - Use
while
when exit condition depends on logic - Use
foreach
for looping through arrays - Avoid infinite loops by making sure conditions change
0 Comments