Labs ICT
โญ Pro Login

Loops

Loops let you repeat code without copying and pasting. Need to print numbers 1 through 100? Write the echo once inside a loop. Need to process every item in an array? Loop through it. Loops are one of those things that seem basic but unlock everything.

PHP has four loop types. Each has a specific job, but they all do the same core thing: run a block of code multiple times based on a condition.

The for Loop

Use for when you know exactly how many times you want to loop. It takes three parts: initialization, condition, and increment. They go inside the parentheses separated by semicolons.


<?php
for ($i = 1; $i <= 5; $i++) {
  echo "Count: $i";
}
?>
    
Try it Yourself โ†’

$i = 1 sets the starting point. $i <= 5 is the condition checked each time. $i++ runs after each iteration. On the sixth check, $i is 6, the condition fails, and the loop stops.

while and do-while

while checks the condition first, then runs the code if it's true. do-while runs the code first, then checks the condition. That means do-while always runs at least once, even if the condition is false from the start.


<?php
$x = 1;

while ($x <= 5) {
  echo "While: $x";
  $x++;
}

$y = 1;

do {
  echo "Do-while: $y";
  $y++;
} while ($y <= 5);
?>
    

foreach โ€” The Array King

This is the loop you'll use most with PHP. foreach is designed specifically for arrays. It loops through each element without needing a counter or condition. For indexed arrays, you get the value. For associative arrays, you get both key and value.


<?php
$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {
  echo $fruit;
}

$user = ["name" => "Bilal", "age" => 25, "city" => "Kano"];

foreach ($user as $key => $value) {
  echo "$key: $value";
}
?>
    

break and continue

break exits the loop entirely. continue skips the rest of the current iteration and moves to the next one. These let you control loop flow from inside the loop body.


<?php
for ($i = 1; $i <= 10; $i++) {
  if ($i == 5) {
    break;  // stops at 4
  }
  echo $i;
}

for ($i = 1; $i <= 5; $i++) {
  if ($i == 3) {
    continue;  // skips 3
  }
  echo $i;  // prints 1, 2, 4, 5
}
?>
    

๐Ÿงช Quick Quiz

Which loop is best suited for iterating over every element of an array in PHP?