Loops
⏱ 15 min read read
for Loop:
PHP uses C-style for loops. This is the same syntax as Java.
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5
while Loop:
$n = 1;
while ($n <= 100) {
$n *= 2;
}
echo $n; // 128
do-while Loop:
Always executes the body at least once before checking the condition.
do {
$input = readline("Enter 'quit' to stop: ");
} while ($input !== 'quit');
foreach Loop --- PHP's Most Important Loop:
foreach is designed for arrays and is the standard way to iterate in
PHP.
// Simple array
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// Associative array --- key => value
foreach ($scores as $name => $score) {
echo "$name: $score\n";
}
// With index
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit\n";
}
PHP's foreach is the equivalent of Python's for...in loop.
It works on arrays and objects implementing Traversable.
No range() function needed --- use for ($i=0; ...) or range(1,5).
break and continue:
break --- exits the loop. Can take a number: break 2 exits two nested
loops.
continue --- skips current iteration. continue 2 skips in outer loop.
PHP uses C-style for loops. This is the same syntax as Java.
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5
while Loop:
$n = 1;
while ($n <= 100) {
$n *= 2;
}
echo $n; // 128
do-while Loop:
Always executes the body at least once before checking the condition.
do {
$input = readline("Enter 'quit' to stop: ");
} while ($input !== 'quit');
foreach Loop --- PHP's Most Important Loop:
foreach is designed for arrays and is the standard way to iterate in
PHP.
// Simple array
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// Associative array --- key => value
foreach ($scores as $name => $score) {
echo "$name: $score\n";
}
// With index
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit\n";
}
PHP's foreach is the equivalent of Python's for...in loop.
It works on arrays and objects implementing Traversable.
No range() function needed --- use for ($i=0; ...) or range(1,5).
break and continue:
break --- exits the loop. Can take a number: break 2 exits two nested
loops.
continue --- skips current iteration. continue 2 skips in outer loop.
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress