PHP Loops

while, do-while, for and foreach.

✍️ 2 exercises in this lesson
  • while: loops while a condition is true.
  • do...while: runs once, then checks the condition.
  • for: loops a fixed number of times.
  • foreach: loops through arrays, with or without keys.

break stops a loop; continue skips to the next iteration.

Key Takeaways: PHP Loops

Mastering PHP Loops helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Loops Code Example

PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    echo "Lap $i<br>";
}

$skills = ["PHP", "MySQL", "Laravel"];
foreach ($skills as $skill) {
    echo "I know $skill<br>";
}

$prices = ["tea" => 50, "coffee" => 120];
foreach ($prices as $item => $price) {
    echo "$item costs Rs $price<br>";
}
Output
Lap 1
Lap 2
Lap 3
I know PHP
I know MySQL
I know Laravel
tea costs Rs 50
coffee costs Rs 120
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Loops Practice Exercises

Check what you learned in “PHP Loops”.

/ 2 solved
Fill in the blank

Loop through an array with keys and values.

 ($prices as $item => $price) { }
✓ Correct! Not quite. Try again.
Multiple choice

Which loop always runs at least once?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services