Loops
C-style for loop
The classic three-part for loop:
ZYMBA
for ($i = 0; $i < 5; $i++) {
echo "$i ";
}
// Output: 0 1 2 3 4
All three parts are expressions — you can use any step value:
ZYMBA
// Count down
for ($i = 10; $i > 0; $i -= 3) {
echo "$i ";
}
// Output: 10 7 4 1
// Step by 2
for ($i = 0; $i < 10; $i += 2) {
echo "$i ";
}
// Output: 0 2 4 6 8
for-as loop (array iteration)
Iterate over arrays and objects with for...as:
ZYMBA
// Iterate values only
$colors = ["red", "green", "blue"];
for ($colors as $color) {
echo "$color ";
}
// Output: red green blue
// Iterate key-value pairs
$person = [name: "Alice", age: 30, city: "NYC"];
for ($person as $key: $value) {
echo "$key=$value ";
}
// Output: name=Alice age=30 city=NYC
Array destructuring in loops
Unpack nested arrays directly in the loop variable:
ZYMBA
$points = [[name: "a", price: 10], [name: "b", price: 20]];
for ($points as [$name, $price]) {
echo "$name=$price ";
}
// Output: a=10 b=20
This is commonly used when iterating database results:
ZYMBA
$rows = [
[id: 1, name: "Widget", price: 9.99],
[id: 2, name: "Gadget", price: 19.99]
];
for ($rows as $row) {
echo "$row.name: $row.price\n";
}
while loop
Execute code as long as a condition is true:
ZYMBA
$counter = 0;
while ($counter < 5) {
echo "$counter ";
$counter++;
}
// Output: 0 1 2 3 4
do-while loop
Execute the body at least once, then repeat while the condition is true:
ZYMBA
$i = 0;
do {
echo "$i ";
$i++;
} while ($i < 3);
// Output: 0 1 2
Useful for retry patterns and paginated API requests:
ZYMBA
$offset = 0;
do {
$batch = $fetchBatch($offset);
$processBatch($batch);
$offset += count $batch;
} while (count $batch >= 100);
loop (infinite loop)
The loop keyword creates an infinite loop — use break to exit:
ZYMBA
$attempts = 0;
loop {
$attempts++;
$result = $tryConnect();
if ($result) {
break;
}
if ($attempts >= 3) {
throw new @Exception("Connection failed after 3 attempts");
}
}
break
Exit the current loop immediately:
ZYMBA
$items = ["apple", "banana", "cherry", "date"];
for ($items as $item) {
if ($item == "cherry") {
break;
}
echo "$item ";
}
// Output: apple banana
continue
Skip the rest of the current iteration and move to the next:
ZYMBA
$numbers = [1, 2, 3, 4, 5, 6];
for ($numbers as $n) {
if ($n % 2 == 0) {
continue; // Skip even numbers
}
echo "$n ";
}
// Output: 1 3 5
A practical example — skipping invalid records:
ZYMBA
for ($records as $record) {
unless (exists $record.email) {
continue;
}
unless ($record.email ~= "/^[^@]+@[^@]+$/") {
continue;
}
$processRecord($record);
}