PHP Loops: foreach, for, while, and do-while

Last updated: August 27, 2026.

PHP provides several loop structures. Use foreach for arrays and iterables, for for counters, and while when repetition depends on a condition.

foreach for arrays

<?php
$prices = ['book' => 18.50, 'pen' => 2.25, 'notebook' => 6.75];

foreach ($prices as $item => $price) {
    echo htmlspecialchars($item) . ': $' . number_format($price, 2) . PHP_EOL;
}
?>

for with a counter

<?php
for ($page = 1; $page <= 5; $page++) {
    echo "Processing page {$page}" . PHP_EOL;
}
?>

while and do-while

<?php
$attempts = 0;

while ($attempts < 3) {
    $attempts++;
    echo "Attempt {$attempts}" . PHP_EOL;
}

do {
    $value = random_int(1, 6);
} while ($value !== 6);
?>

Control loop execution

<?php
foreach ([5, -2, 8, 0, 12] as $value) {
    if ($value < 0) {
        continue;
    }
    if ($value === 0) {
        break;
    }
    echo $value . PHP_EOL;
}
?>

Use continue to skip an iteration and break to exit the current loop. See the PHP manual’s foreach and for references.

admin

admin

Leave a Reply

Your email address will not be published.