PHP Tutorial menu

PHP Loops

A loop runs the same code again and again, so you do not have to write it many times.

Types of Loops

LoopUse it when
whileYou repeat while a condition is true
do...whileLike while, but the code runs at least once
forYou know how many times to repeat
foreachYou go through every item in an array

The while Loop

Example

php
<?php
$i = 1;
while ($i <= 5) {
    echo "Lesson $i<br>";
    $i++;
}
Output
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5

Always change the variable inside the loop (here $i++). If the condition never becomes false, you get an infinite loop and the page never finishes loading.

The do...while Loop

The condition is checked after the code, so the code runs at least once:

Example

php
<?php
$tries = 10;
do {
    echo "Attempt number $tries<br>";
    $tries++;
} while ($tries < 5);
Output
Attempt number 10

The for Loop

A for loop puts the start, the condition and the step on one line:

Example

php
<?php
// Multiplication table of 7
for ($n = 1; $n <= 5; $n++) {
    echo "7 x $n = " . (7 * $n) . "<br>";
}
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

The foreach Loop

foreach is the easiest way to go through an array:

Example

php
<?php
$courses = ["Web Development", "Graphic Designing", "SEO"];

foreach ($courses as $course) {
    echo "- $course<br>";
}
Output
- Web Development
- Graphic Designing
- SEO

With keys and values:

Example

php
<?php
$prices = ["Tea" => 80, "Paratha" => 60, "Samosa" => 30];

foreach ($prices as $item => $price) {
    echo "$item: Rs $price<br>";
}
Output
Tea: Rs 80
Paratha: Rs 60
Samosa: Rs 30

break and continue

  • break stops the loop completely
  • continue skips the rest of this round and goes to the next one

Example

php
<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 === 0) {
        continue;   // skip even numbers
    }
    if ($i > 7) {
        break;      // stop after 7
    }
    echo "$i ";
}
Output
1 3 5 7

Adding Up with a Loop

Example

php
<?php
$marks = [78, 85, 62, 90];
$total = 0;

foreach ($marks as $m) {
    $total += $m;
}

echo "Total: $total, Average: " . ($total / count($marks));
Output
Total: 315, Average: 78.75

Exercise

Exercise

Which loop is best for going through every item of an array?

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp