Introduction
Imagine printing the numbers 1 to 100 by writing 100 echo lines. Or building a list of 50 students by copying one block 50 times. That is not programming — that is typing. A loop repeats a block of code for you, as many times as you say.
PHP gives you three loops. for is for when you know how many rounds you need — count from 1 to 10. while is for when you do not know — keep going until something becomes true. foreach is for walking through an array, one item at a time — the loop you will use most in real PHP, because real PHP is mostly lists of things.
Every loop needs a way to stop. A loop that never stops is an infinite loop: the page hangs, the server works forever, and you have to kill it. The rule is simple — every loop must move towards its own ending.
(Roman Urdu: Loop ka matlab hai "dohrana" — aik hi kaam baar baar, likhe baghair. for gin-ti ke liye, while jab tak ke liye, foreach fehrist ke liye.)
Key points
- A
forloop has three parts in its head: start ($i = 1), condition ($i <= 5), update ($i++). All three sit in one line. - A
whileloop checks its condition before every round. If the condition starts false, the block never runs. - A
do...whileloop runs once first, then checks. Useful when the first round must happen no matter what. foreachwalks an array one item at a time:foreach ($fruits as $fruit)gives you each value in$fruit.foreach ($arr as $key => $value)gives you the key as well — vital for associative arrays.breakleaves the loop completely.continueskips only this round and jumps to the next.$i++adds 1;$i--subtracts 1. Forgetting the update is how infinite loops are born.- A loop counter usually starts at 0 for arrays (because array indexes start at 0) and at 1 for human counting.
- Loops can sit inside loops (nested loops) — for example, a table with rows and columns — but keep them shallow.
- Never trust a
whilecondition you cannot see changing. Before you run it, point at the line that changes the condition and say it out loud.
Examples
Example 1 — for: count 1 to 5
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}
?>What you will get:
1
2
3
4
5$i starts at 1, the block runs while $i <= 5, and $i++ adds 1 after each round. When $i becomes 6, the condition is false and the loop stops.
Example 2 — while: fill cups until the jug is empty
<?php
$cups = 0;
while ($cups < 3) {
$cups++;
echo "Cup $cups filled<br>";
}
echo "Done";
?>What you will get:
Cup 1 filled
Cup 2 filled
Cup 3 filled
DoneThe condition is checked before every round. If $cups had started at 3, nothing would print at all.
Example 3 — foreach: read a list
<?php
$fruits = ["apple", "banana", "mango"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>What you will get:
apple
banana
mangoNo counting, no indexes, no chance of an off-by-one error. foreach handles the walking; you handle what happens to each item.
Example 4 — foreach with keys
<?php
$marks = ["Ali" => 88, "Sara" => 92, "Bilal" => 76];
foreach ($marks as $name => $score) {
echo "$name: $score<br>";
}
?>What you will get:
Ali: 88
Sara: 92
Bilal: 76With $key => $value you get the label and the value together. This is the shape of almost every list page you will ever build: a loop over rows, printing one line per row.
Example 5 — break and continue
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 3) {
continue; // skip 3
}
if ($i == 7) {
break; // stop at 7
}
echo $i . " ";
}
?>What you will get:
1 2 4 5 6continue skips round 3 only — 3 never prints. break leaves the loop at 7, so 7, 8, 9 and 10 never print.
Example 6 — A loop that builds an HTML list
<?php
$students = ["Ali", "Sara", "Bilal", "Hira"];
echo "<ul>";
foreach ($students as $student) {
echo "<li>$student</li>";
}
echo "</ul>";
?>What you will get:
• Ali
• Sara
• Bilal
• HiraThis is the real pattern: PHP loops over data and prints HTML around it. The browser receives a finished list; it never knows a loop was involved.
Quick recap
forcounts a known number of rounds: start, condition, update in one head.whilerepeats until its condition turns false — the update must live inside.foreachwalks an array item by item;$key => $valuegives the key too.breakleaves the loop;continueskips one round.- Every loop must move towards its ending, or it never stops.
Common mistakes
- Forgetting the update in a while loop —
while ($i < 5)with no$i++inside runs forever and hangs the page. Fix: put the update inside the loop, and test with a small limit first. - Writing
for ($i = 1; $i <= 5; $i--)— the counter shrinks, the condition stays true, the loop never ends. Fix: the update must move towards the condition's end. - Off-by-one errors —
for ($i = 0; $i <= 3; $i++)on a 3-item array tries index 3, which does not exist. Fix: for arrays use$i < count($arr), not<=. - Using
$iafter the loop and expecting the last value — after the loop$iholds the value that failed the condition (6 after counting to 5). Fix: save the value you need inside the loop. - Modifying an array while foreach walks it — adding or removing items mid-loop gives surprising results. Fix: build a new array, or loop over a copy.
- Nesting loops and reusing
$ifor both — the inner loop destroys the outer counter. Fix: use different counters, like$ioutside and$jinside. - Echoing inside a loop without
<br>or a separator — all values run together on one line. Fix: print a separator, a<br>, or wrap each item in an HTML tag.
Practice
- Write a
forloop that prints the numbers 1 to 10, one per line. - Write a
whileloop that prints the even numbers from 2 to 20. - Make an array of 5 fruits and print each one with
foreach, numbered 1 to 5. - Make an associative array of 3 students and their marks, and print "Name: marks" for each with
foreach ($marks as $name => $score). - Print the numbers 1 to 20 but skip the multiples of 3 with
continue. - Search an array of names for "Sara" with a loop and
breakas soon as you find her — print "Found at position X". - Deliberately write a
whileloop with no update, run it, and stop the page load — then fix it and write down, in one line, why the update matters. (Keep the limit small:while ($i < 3).)
Practice quiz
Tap an answer to check it — a right answer turns green, a wrong one turns red and shows the right answer. Nothing is scored or saved; this is just for practice.
1. When do you use a for loop?
2. What happens if a while loop never updates its condition?
3. What is the difference between break and continue in a loop?