Loops
PHP supports for, while, do-while, and foreach loops, the last of which is especially common for iterating over arrays.
for, while, and do-while
These loop types behave just as they do in most C-family languages, repeating a block based on a condition that's checked before (for/while) or after (do-while) each iteration.
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i\n";
}
$attempts = 0;
while ($attempts < 3) {
echo "Attempt " . ($attempts + 1) . "\n";
$attempts++;
}
foreach — Iterating Arrays
foreach is the most common loop in everyday PHP, purpose-built for walking through every element of an array without manually managing an index.
$fruits = ["Apple", "Banana", "Mango"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
$prices = ["Apple" => 12, "Banana" => 8];
foreach ($prices as $name => $price) {
echo "$name costs R$price\n";
}
Common Mistakes
- Using a for loop with manual indexing to walk an array when foreach would be simpler and less error-prone.
- Forgetting that modifying an array while iterating it with foreach can produce unexpected results unless done carefully with a reference.
- Writing an infinite loop by forgetting to update the loop's condition variable.
- Confusing => (used in foreach for key-value pairs) with -> (used to access object properties).
Professional Tip
Reach for foreach by default whenever you need to process every item in an array. It's clearer, less error-prone, and is idiomatic PHP compared to manually managing a counter with a for loop.
Your Turn
Create an associative array of three products and their prices, then use foreach to print each product name alongside its price formatted as currency.
Mini Quiz
Which loop type is specifically designed for iterating over the elements of an array?
foreach was built specifically for array iteration, automatically handling each element (and optionally its key) without manual index tracking.