Loops
By the end of this lesson you'll repeat work without copy-pasting — counting with for , waiting on a condition with while and do-while , and walking through arrays with foreach , the loop you'll reach for most in real PHP.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free Php course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
1️⃣ The for Loop — Counting
A loop runs the same block of code over and over so you don't have to copy-paste it. The for loop is the one to use when you know how many times to repeat. Its header has three parts inside the brackets, separated by semicolons: a start value, a condition checked before each pass, and a step that runs after each pass. The $i++ step means "add 1 to $i ".
Read the header as: start at 1, keep going while $i = 5 , and add 1 each time. When $i hits 6 the condition is false, the loop ends, and the code after it runs once.
2️⃣ The while Loop — Repeat Until Done
Sometimes you don't know the count in advance — you just want to keep going until something happens . That's the while loop: it checks a condition before each pass and repeats as long as it's true. The golden rule: something inside the loop must move you toward the condition becoming false, or the loop never ends.
Here $total += 20 grows the total every pass, so the condition $total 100 eventually turns false and the loop stops. Take that line out and you'd have an infinite loop .
3️⃣ The do-while Loop — Run At Least Once
A do-while loop is a while loop flipped upside down: it runs the body first , then checks the condition at the bottom. Because of that, the body always runs at least once — even if the condition was false from the very start. It's the right choice whenever the work must happen one time before you decide whether to repeat (think "show the menu, then ask if they want it again").
4️⃣ foreach — Walking an Array
This is the loop you'll use most in PHP. An array is an ordered list of values, and foreach hands you each one in turn — no counter, no index, no off-by-one mistakes. The simplest form is foreach ($arr as $value) : on each pass, your variable (here $fruit ) holds the next item.
5️⃣ foreach with Keys — $key => $value
Every array item has a key (its label) as well as a value. In a plain list the keys are positions — 0, 1, 2… In an associative array the keys are names you chose, like "coffee" . The form foreach ($arr as $key => $value) gives you both at once: the part before => is the key, the part after is the value.
Notice 3.50 printed as 3.5 — PHP drops a trailing zero when it shows a number. To force two decimals (real money) you'd use number_format($price, 2) or printf , which you'll see in the order example below.
6️⃣ break & continue — Steering the Loop
break leaves the loop completely — handy once you've found what you were looking for. continue skips just the rest of the current pass and jumps to the next one. When loops are nested (a loop inside a loop), you can add a number: break 2 breaks out of two loops at once, and continue 2 jumps to the next pass of the outer loop.
Now you try. The script below counts down , so the condition and step are different from a normal count-up. Fill in each ___ using the 👉 hint, then run it and check it against the Output panel.
One more — this time practise the key => value form. Name the key and value variables so the echo already in the code lines up.
7️⃣ Alternative Syntax — endforeach & endfor
PHP lets you swap the curly braces {' '} for a colon and a matching end word : foreach (…): … endforeach; and for (…): … endfor; Both forms do exactly the same thing. This style shines when a loop is wrapped around HTML in a template , because a named endforeach; is far easier to pair up than a lone '} buried among tags.
8️⃣ Putting It Together — An Order Total
Here's the whole lesson in one realistic snippet: a foreach over a cart with named keys, a continue to skip out-of-stock items, and a running total. This is the exact shape of code you'd write to add up a real shopping basket.
📋 Quick Reference — PHP Loops
No code is filled in this time — just a brief and an outline. FizzBuzz is the most famous loop exercise in programming, and it's a rite of passage. Write it yourself, run it on onecompiler.com/php or your own machine, then check your result against the expected output in the comments.
Practice quiz
Which loop is best when you know exactly how many times to repeat?
- while
- do-while
- for
- foreach
Answer: for. A for loop, with its start/condition/step header, is ideal for a known number of repetitions.
What are the three parts inside a for loop header, in order?
- start, check, step
- check, step, start
- step, start, check
- start, step, check
Answer: start, check, step. The header is start (e.g. $i = 1), check (e.g. $i <= 5), then step (e.g. $i++).
How does a do-while loop differ from a while loop?
- It never runs
- It cannot use a condition
- It only loops over arrays
- It always runs the body at least once
Answer: It always runs the body at least once. do-while checks the condition AFTER the body, so the body always runs at least once.
Which loop is the most-used way to walk through an array?
- for
- foreach
- do-while
- repeat
Answer: foreach. foreach hands you each element in turn with no index or off-by-one mistakes.
In foreach ($arr as $key => $value), what does the part before => give you?
- The key
- The value
- The array length
- The next item
Answer: The key. The part before => is the key; the part after is the value.
What does the continue statement do inside a loop?
- Stops the loop completely
- Restarts the loop from the start
- Skips the rest of the current pass and goes to the next
- Pauses the script
Answer: Skips the rest of the current pass and goes to the next. continue skips the rest of the current iteration and jumps to the next one.
What does break 2 do inside two nested loops?
- Breaks only the inner loop
- Breaks out of both loops at once
- Skips two iterations
- Causes an error
Answer: Breaks out of both loops at once. The number after break is how many nested loops to exit, so break 2 leaves both.
What does this print? for ($i=1; $i<=6; $i++) { if ($i % 2 === 0) continue; echo $i; }
- 123456
- 246
- 1357
- 135
Answer: 135. continue skips even numbers, so only the odd values 1, 3, 5 are printed: 135.
What usually causes an infinite loop?
- Using foreach
- Forgetting to change the variable the condition depends on
- Adding a break
- Using a for loop
Answer: Forgetting to change the variable the condition depends on. If nothing in the body moves toward the condition becoming false, the loop runs forever.
Which keyword closes a foreach written with the alternative template syntax?
- endwhile;
- endfor;
- endforeach;
- end;
Answer: endforeach;. The alternative syntax closes a foreach loop with endforeach;.