Home Quizzes Leaderboard Competitions Learn Hire Us
About Contact
Log In Sign Up
Learn PHP Loops

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.
Code Example
<?php

// for loop --- C-style (same as Java)

for ($i = 1; $i <= 5; $i++) {

echo $i . " ";

}

echo "\n"; // 1 2 3 4 5

// Count down

for ($i = 5; $i >= 1; $i--) {

echo $i . " ";

}

echo "Liftoff!\n"; // 5 4 3 2 1 Liftoff!

// while loop

$number = 1;

while ($number <= 100) {

$number *= 2;

}

echo "First over 100: $number\n"; // 128

// break --- stop at 5

for ($i = 1; $i <= 10; $i++) {

if ($i === 5) break;

echo $i . " ";

}

echo "\n"; // 1 2 3 4

// continue --- skip even numbers

for ($i = 1; $i <= 10; $i++) {

if ($i % 2 === 0) continue;

echo $i . " ";

}

echo "\n"; // 1 3 5 7 9

// foreach --- simple array

$fruits = ["apple", "banana", "cherry"];

foreach ($fruits as $i => $fruit) {

echo ($i + 1) . ". $fruit\n";

}

// foreach --- associative array (key => value)

$scores = ["Alice" => 92, "Bob" => 78, "Carol" => 85];

foreach ($scores as $name => $score) {

echo "$name: $score\n";

}

// range() equivalent

foreach (range(1, 5) as $n) {

echo $n . " ";

}

echo "\n"; // 1 2 3 4 5

?>
← If Statements & Conditionals Arrays →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress