A loop is a structure that repeats a block of code as long as a condition is met or as long as there are elements left to go through.
Imagine you have an online store with 5,000 products and you want to lower the price of all of them by 10%. You’re not going to write 5,000 lines of code one by one.
That’s why loops (or iterative structures) exist: we define a logic once and apply it to a set of data as many times as necessary.
In PHP we have three main tools. Let’s see when to use each one.
while: “as long as this is true…”
It’s the most basic loop. It executes the code while the condition is true.
$counter = 1;
while ($counter <= 5) {
echo "Round number $counter \n";
$counter++; // We advance the counter
}The danger: the infinite loop
If you forget to put $counter++, the condition $counter <= 5 will always be true. Your script will never finish, your server will become “hung” consuming CPU, and you’ll have to kill it. Be very careful with exit conditions.
When to use while?
When you don’t know in advance how many times you have to repeat something.
- Example: “Read lines from this file until the end is reached”.
- Example: “Try an operation a limited number of times while it keeps failing”.
for: the precision counter
It’s the classic Swiss Army knife. It condenses the while logic into a single line.
Structure: for (initialization; condition; increment)
for ($i = 0; $i < 10; $i++) {
echo "The square of $i is " . ($i ** 2) . "\n";
}When to use for?
When you know exactly how many times you want to iterate or you need a numeric counter. It’s ideal for math, sequences, or generating HTML tables.
foreach: the king of arrays (and of PHP)
This is where PHP shines. Whereas in C or old Java you had to use for to go through lists, in PHP we use foreach. It’s cleaner, safer, and easier to read.
foreach takes a set of data (an array or an object) and goes through it element by element. You don’t need counters.
Option a: only the value
$fruits = ['Apple', 'Pear', 'Banana'];
foreach ($fruits as $fruit) {
echo "I have a $fruit \n";
}Option b: key and value
Sometimes you need to know the index or the key of the array (e.g., a user’s ID).
$user = [
'name' => 'Luis',
'role' => 'Admin',
'web' => 'luisllamas.es'
];
foreach ($user as $key => $value) {
echo "$key: $value \n";
}
// Output:
// name: Luis
// role: Admin...When to use foreach?
Use foreach whenever you work with arrays or collections of data. It avoids the error of going out of bounds, which is very common with for.
Technical depth: modifying data inside the loop
By default, foreach works with a copy of the value. If you change the value inside the loop, the original array does not change.
$prices = [10, 20, 30];
foreach ($prices as $price) {
$price = $price * 2; // We only modify the temporary variable
}
// $prices is still [10, 20, 30]If you want to modify the original array, you need to use references by prepending &:
foreach ($prices as &$price) { // Notice the &
$price = $price * 2;
}
// Now $prices is [20, 40, 60]
unset($price); // IMPORTANT! Break the referenceWhen you use & (references), after the loop ends the variable $price remains “hooked” to the last element of the array. If you use it later by mistake, you will modify the array unintentionally. Always do unset($variable) after finishing a loop by reference.
break and continue: controlling the traffic
Sometimes you don’t want to end the entire loop.
break: “Stop the cart”. It completely breaks the loop and exits.continue: “Skip this round”. It stops executing the current iteration and moves on to the next one.
$target = 'Pear';
$basket = ['Apple', 'Rotten', 'Pear', 'Grape'];
foreach ($basket as $fruit) {
if ($fruit === 'Rotten') {
continue; // Yuck! We skip this and continue
}
if ($fruit === $target) {
echo "Found it!";
break; // I have it, I stop searching
}
}