PHP Loops
⭐ PHP Loops
PHP Loops allow you to execute a block of code multiple times, until a condition is met.
PHP supports 4 main types of loops:
-
while loop
-
do…while loop
-
for loop
-
foreach loop
Let’s understand each one with examples.
🔁 1. PHP while Loop
Runs as long as the condition is true.
Syntax:
Example:
Output:1 2 3 4 5
🔁 2. PHP do…while Loop
Runs the code at least once, even if the condition is false.
Syntax:
Example:
Output:6
(Runs once before checking the condition)
🔁 3. PHP for Loop
Used when you know exactly how many times to loop.
Syntax:
Example:
Output:1 2 3 4 5
🔁 4. PHP foreach Loop
Used ONLY for arrays.
Syntax:
Example:
Output:red green blue
foreach with key and value:
➕ Additional Controls: break & continue
✔️ break
Stops the loop completely.
✔️ continue
Skips the current iteration.
🔁 Nested Loops
A loop inside another loop.
Example:
📌 Summary Table
| Loop Type | When to Use |
|---|---|
| while | When condition is checked first |
| do…while | Must run at least once |
| for | Definite number of iterations |
| foreach | Loop through arrays |
If you want, I can continue with the next topic:
👉 PHP Arrays
👉 PHP Functions
👉 PHP Forms (GET & POST)
👉 PHP Include & Require
