PHP Loops

PHP loops repeat a block of code. You will use them to walk through arrays, database rows, or any task that happens many times. PHP has four loop types: for, while, do...while and foreach.

The For Loop

Use for when you know how many times to repeat. It has an initializer, a condition and a step.

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Row $i\n";
}
Row 1
Row 2
Row 3
Row 4
Row 5

The While and Do While Loops

while checks the condition before each run. do...while runs the body at least once, then checks.

<?php
$balance = 100;
$months = 0;
while ($balance < 150) {
    $balance *= 1.1;
    $months++;
}
echo "$months months\n";

$n = 10;
do {
    echo "runs once: $n";
} while ($n < 5);
5 months
runs once: 10

The PHP Foreach Loop

foreach is the loop you will use most. It goes through every element of an array, optionally giving you the key too.

<?php
$prices = ['tea' => 2.5, 'coffee' => 3.0, 'juice' => 4.25];

foreach ($prices as $item => $price) {
    echo str_pad($item, 8) . number_format($price, 2) . "\n";
}
tea     2.50
coffee  3.00
juice   4.25

Break and Continue

break exits the loop completely. continue skips to the next iteration.

<?php
foreach ([3, 8, -1, 12, 0, 7] as $n) {
    if ($n < 0) continue;
    if ($n === 0) break;
    echo $n, " ";
}
3 8 12 

Modifying Arrays in Foreach

By default foreach works on a copy of each value. Add & to change the original array, and unset the reference afterwards to avoid bugs. Often array_map() is a cleaner choice.

<?php
$nums = [1, 2, 3];
foreach ($nums as &$n) {
    $n *= 10;
}
unset($n);
echo implode(",", $nums);
10,20,30

Frequently asked questions

Which loop is best for arrays in PHP?

foreach. It is simpler and safer than for because it does not need an index or count.

How do I get the index in a PHP foreach loop?

Use the key syntax: foreach ($array as $index => $value). For lists the key is the numeric index.

How do I stop an infinite while loop?

Make sure something inside the loop changes the condition, or use break. In a terminal, press Ctrl+C to stop a running script.