PHP Loops
# Chapter 8: PHP Loops
1. Introduction
Welcome to Chapter 8! One of the greatest strengths of a computer is its ability to perform repetitive tasks incredibly fast without complaining. If you need to write "I will not throw paper in class" 100 times, you could write 100echo statements. Or, you could write a loop! Loops execute a block of code a specified number of times, or as long as a certain condition remains true. In this chapter, we will learn about the while, do...while, for, and foreach loops.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Use a
whileloop to execute code as long as a condition is true.
-
Use a
forloop to execute code a specific number of times.
-
Understand how
do...whileguarantees at least one execution.
-
Briefly introduce the
foreachloop (which we will master in the Arrays chapter).
-
Control loop flow using
breakandcontinue.
3. The while Loop
The while loop loops through a block of code as long as the specified condition evaluates to true.
4. The do...while Loop
This loop will always execute the block of code at least once, and then it will repeat the loop as long as the specified condition is true. It evaluates the condition at the *end* of the loop, not the beginning.
5. The for Loop
The for loop is best used when you know exactly in advance how many times the script should run. It packs the initialization, condition, and increment into a single neat line.
6. Controlling Loops: Break and Continue
Sometimes you need to interrupt a loop before it finishes naturally.-
break: Exits the loop entirely immediately.
-
continue: Skips the rest of the current iteration and jumps straight to the next iteration.
7. Real-World Examples
Imagine you are building a dropdown menu for a user's birth year on a registration form. Typing 100<option> tags manually would be terrible. Let PHP do the heavy lifting!
8. Output Explanations
In the dropdown example, thefor loop starts at 2026. The condition checks if $year >= 1900. Since it is, it outputs the <option> tag for 2026. Then $year-- subtracts 1, making it 2025. It repeats this process 127 times almost instantly, generating a complete HTML dropdown menu.
9. Common Mistakes
-
Infinite Loops: If you forget to update your counter variable (like forgetting
$i++in a while loop), the condition will ALWAYS be true. The loop will run forever until the server crashes or times out.
-
Off-by-One Errors: Using
< 10when you actually meant<= 10. If you want to run exactly 10 times starting from 1, you must use<=.
-
Misplacing semicolons: Writing
for ($i=0; $i<5; $i++); { ... }(notice the semicolon before the brace). This breaks the loop syntax.
10. Best Practices
-
Use a
forloop when you know the exact number of iterations.
-
Use a
whileloop when reading data from a file or a database where you don't know in advance how many rows exist.
- Keep the logic inside your loops as lightweight as possible. Running complex database queries inside a loop 10,000 times will bring your server to a halt.
11. Exercises
-
1.
Write a
whileloop that counts backwards from 10 to 1, and then echoes "Blastoff!".
-
2.
Write a
forloop that outputs only EVEN numbers between 1 and 20. (Hint: increment by 2, or use the%modulus operator).
12. Mini Project: Multiplication Table Generator
Task: Create an HTML table that displays the multiplication table for the number 7 using a loop.13. Coding Challenges
Challenge 1: Use awhile loop to sum up all the numbers from 1 to 50. Echo the final total.
14. MCQs with Answers
1. Which loop is guaranteed to execute its code block at least once? A)for loop
B) while loop
C) do...while loop
D) infinite loop
*Answer: C*
2. What causes an infinite loop?
A) Using the break keyword.
B) Forgetting to increment or change the condition variable so it never becomes false.
C) Putting a loop inside another loop.
D) Using continue.
*Answer: B*
3. What does the continue statement do in a loop?
A) Exits the loop entirely.
B) Pauses the loop for 1 second.
C) Restarts the loop from the very beginning.
D) Skips the current iteration and jumps to the next iteration.
*Answer: D*
15. Interview Questions
Q: What is the main difference between afor loop and a while loop?
*A:* A for loop is typically used when the number of iterations is known before entering the loop, as the counter initialization, condition, and increment are all bundled together. A while loop is used when the number of iterations is unknown, and it runs strictly as long as a condition remains true (like reading file lines until the end of the file is reached).
Q: How does the foreach loop differ from the others?
*A:* We will cover it deeply later, but foreach is specifically designed to iterate over arrays and objects. It automatically loops through every item in an array without needing a counter variable or an exit condition.
16. FAQs
Q: Can I put anif statement inside a loop?
*A:* Yes! This is very common. You can nest loops inside loops, and if statements inside loops, to create highly complex logic structures.
17. Summary
You've unlocked automation! You learned how to usewhile and do...while loops for condition-based repetition, and for loops for counter-based repetition. You built dynamic HTML using loops and learned how to control loop flow using break and continue.