Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Loops

A loop repeats the same code several times. You need one to process a list of products, print table rows or compute a sum — without a loop you would have to copy the code by hand.

while

The while loop repeats a block as long as the condition is true. The condition is checked before every pass:

<?php
 
$i = 1;
 
while ($i <= 3) {
    echo $i, "\n";
    $i++;
}

The variable $i is called a counter. It must change inside the loop, otherwise the condition never becomes false.

for

When the number of passes is known in advance, for is more convenient. The parentheses hold three parts separated by semicolons: the initial value, the condition and the step:

<?php
 
for ($i = 1; $i <= 3; $i++) {
    echo "Step $i\n";
}

This loop does the same as the while above, but all the counter handling sits on one line.

foreach

The foreach loop walks through the elements of an array one at a time. On each pass the next element is placed in a variable:

<?php
 
$fruits = ['apple', 'pear', 'plum'];
 
foreach ($fruits as $fruit) {
    echo $fruit, "\n";
}

No counter is needed: the loop ends by itself when the elements run out. Arrays are covered in the next chapter.

Accumulating a result

A common technique is to create a variable before the loop and update it on every pass:

<?php
 
$sum = 0;
 
for ($i = 1; $i <= 5; $i++) {
    $sum += $i;
}
 
echo $sum; // 15

break and continue

break ends the loop early, while continue skips the rest of the current pass and moves on to the next one:

<?php
 
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 === 0) {
        continue;
    }
    if ($i > 7) {
        break;
    }
    echo $i, ' ';
}
// 1 3 5 7

Even numbers are skipped, and the loop stops at nine.

A common mistake

If you forget to change the counter, you get an infinite loop: the condition is always true and the program never stops by itself. On this site such code is interrupted after 5 seconds; on a real server it can keep the CPU busy for a long time.

Thanks for reading!

Donate to the site — we work hard for you.