foreach and Loop Control
Iterate arrays with foreach and use break and continue.
foreach and Loop Control is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
foreach: The Array Loop
foreach is the idiomatic way to iterate over arrays and objects in PHP — no need to track an index manually.
foreach on Indexed Arrays
Iterate over values in an indexed array:
<?php
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
echo $fruit . PHP_EOL;
}
// apple
// banana
// cherryforeach with Key => Value
Get both the key and value in each iteration:
<?php
$person = ['name' => 'Alice', 'age' => 30, 'city' => 'London'];
foreach ($person as $key => $value) {
echo "$key: $value" . PHP_EOL;
}
// name: Alice
// age: 30
// city: LondonNested foreach
Iterate through arrays of arrays (e.g., database result sets):
<?php
$users = [
['name' => 'Alice', 'role' => 'admin'],
['name' => 'Bob', 'role' => 'user'],
];
foreach ($users as $user) {
echo $user['name'] . ' is ' . $user['role'] . PHP_EOL;
}Modifying Array Elements
To modify array values inside foreach, use a reference &$value:
<?php
$prices = [10, 20, 30];
foreach ($prices as &$price) {
$price *= 1.1; // 10% price increase
}
unset($price); // always unset after reference loop!
print_r($prices); // [11, 22, 33]break in foreach
Use break to exit a foreach loop early:
<?php
$ids = [1, 2, 3, 4, 5];
$target = 3;
foreach ($ids as $id) {
if ($id === $target) {
echo 'Found: ' . $id;
break;
}
}continue in foreach
Use continue to skip specific items:
<?php
$numbers = [1, 2, 3, 4, 5, 6];
foreach ($numbers as $n) {
if ($n % 2 === 0) continue; // skip evens
echo $n . ' '; // 1 3 5
}list() with foreach
Destructure inner arrays inline with list() or the shorthand []:
<?php
$coords = [[10, 20], [30, 40], [50, 60]];
foreach ($coords as [$x, $y]) {
echo "x=$x, y=$y" . PHP_EOL;
}
// x=10, y=20
// x=30, y=40Iterating Objects
foreach works on objects — it iterates over public properties by default:
<?php
class Config {
public string $host = 'localhost';
public int $port = 3306;
public string $db = 'myapp';
}
foreach (new Config() as $key => $val) {
echo "$key = $val" . PHP_EOL;
}Generator as foreach Target
PHP generators let you iterate large datasets without loading everything into memory:
<?php
function range100(): Generator {
for ($i = 1; $i <= 100; $i++) {
yield $i;
}
}
foreach (range100() as $num) {
if ($num > 5) break;
echo $num . ' '; // 1 2 3 4 5
}array_walk vs foreach
array_walk applies a callback to every element in place — an alternative to foreach for simple transforms:
<?php
$names = ['alice', 'bob', 'carol'];
array_walk($names, function (&$name) {
$name = ucfirst($name);
});
print_r($names); // ['Alice', 'Bob', 'Carol']Quick Check
When iterating an array by reference in foreach, what should you do after the loop?
Recap: foreach and Loop Control
Key points:
foreach ($arr as $val)for valuesforeach ($arr as $key => $val)for key-value pairs- Use
&$valreference to modify in place — always unset after breakandcontinuework inside foreach- Destructure inner arrays with
[$a, $b] - Generators let foreach process huge datasets memory-efficiently
Frequently asked questions
Is the “foreach and Loop Control” lesson free?
Yes — the full text of “foreach and Loop Control” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “foreach and Loop Control”?
Iterate arrays with foreach and use break and continue. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “foreach and Loop Control” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- if, elseif, and else
- Switch and Match Statements
- for and while Loops
- foreach and Loop Control