← العودة إلى الدورة: PHP from scratch

Loops: for, while, foreach

الفيديو قريبًا

Computers are good at repeating tasks: adding a thousand numbers, showing every product in a catalog, reading a file line by line. Loops let you write the instructions once and run them many times. PHP has four: for, while, do-while and foreach. In web development the most used is foreach, because almost everything you process is lists of data: database rows, form fields, shopping cart items.

for: when you know how many turns

The for loop has three parts separated by semicolons: initialization (runs once), condition (checked before every turn) and increment (runs at the end of every turn). It is ideal for counting. Beware of the classic off-by-one error: for ($i = 0; $i <= 5; $i++) runs six times, not five, because it includes both 0 and 5. To repeat n times, use $i = 0 and $i < n.

php
<?php

declare(strict_types=1);

// Multiplication table of 7
for ($i = 1; $i <= 5; $i++) {
    echo "7 x $i = ", 7 * $i, "\n";
}
// 7 x 1 = 7
// 7 x 2 = 14
// ... up to 7 x 5 = 35

while and do-while

while repeats as long as the condition is true and checks it before every turn; if it is false from the start, the body never runs. do-while checks at the end, so the body runs at least once. Use them when you do not know how many turns there will be: reading until the data ends, retrying an operation, searching for a value. The biggest risk is the infinite loop: if nothing inside the body changes the condition, the program never ends. Always check which variable will make the condition false.

php
<?php

declare(strict_types=1);

// How many times can we halve 100 before it drops below 1?
$value = 100.0;
$steps = 0;

while ($value >= 1) {
    $value /= 2;
    $steps++;
}
echo "Steps: $steps\n"; // Steps: 7

// do-while: the body runs once even if the condition is false
$n = 10;
do {
    echo "n is $n\n"; // printed once
    $n++;
} while ($n < 5);

foreach, break and continue

foreach walks through an array without you managing indexes. With foreach ($list as $item) you get each value; with foreach ($list as $key => $value) you also get the key. Inside any loop, break ends it immediately and continue jumps to the next turn. A good practice is not to modify the array while walking it; if you need a new result, build another array. Arrays are covered in depth in the next lesson, here the bracket syntax is enough.

php
<?php

declare(strict_types=1);

$prices = ['coffee' => 2.5, 'tea' => 1.8, 'juice' => 3.2, 'water' => 1.0];

$total = 0.0;
foreach ($prices as $name => $price) {
    if ($price < 1.5) {
        continue;              // skip cheap items
    }
    if ($name === 'juice') {
        break;                 // stop at juice
    }
    $total += $price;
    echo "$name: $price\n";
}
echo "Total: $total\n";
// coffee: 2.5
// tea: 1.8
// Total: 4.3
  • for: when you know the number of turns (counters, tables).
  • while: when you repeat until something changes and zero turns may happen.
  • do-while: when the body must run at least once.
  • foreach: almost always when you walk an array.

اختبر ما تعلمته

السؤال 1 من 1

How many turns does for ($i = 0; $i <= 5; $i++) make?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →