Thuta Learning
IntermediateProgrammingbeginner

Loops (While, For, Foreach)

Relax. We'll talk through this in plain words — no textbook voice.

A loop lets you run a block of code over and over. Without loops, showing a product list, rendering comments, generating table rows, or looping through array data would leave developers typing overtime by hand.

php
<?php
// For loop: repeat a fixed number of times
for ($i = 1; $i <= 3; $i++) {
  echo "Lesson " . $i . "<br>";
}

// Foreach loop: read every item from an array
$products = ["Laptop", "Mouse", "Keyboard"];
foreach ($products as $product) {
  echo "Product: " . $product . "<br>";
}
?>
You should see
Lesson 1 Lesson 2 Lesson 3 Product: Laptop Product: Mouse Product: Keyboard

Easy traps

  • Forget to add $i++ and the loop won't stop — it'll just keep running.
Loops (While, For, Foreach) | Thuta Learning