PHP ยท Chapter 15 of 44

PHP Loops (while, do-while, for, foreach)

Loops let you run the same block of code multiple times, which is essential for processing lists of data or repeating a task until a condition is met. PHP provides while, do-while, for, and foreach loops.

while checks its condition before each iteration, do-while checks it after (guaranteeing at least one run), for is ideal when you know how many times to loop, and foreach is designed specifically for looping through arrays.

Syntax
for ($i = 0; $i < 5; $i++) { }
foreach ($array as $value) { }

while and do-while

while (condition) { } repeats as long as the condition is true, checked before each pass. do { } while (condition); runs the block once first, then checks the condition.

for and foreach

for (init; condition; increment) { } is useful for counting loops with a known number of iterations. foreach ($array as $value) { } iterates over every element of an array.

Example 1 (php)
<?php
  for ($i = 1; $i <= 3; $i++) {
    echo $i . " ";
  }
?>
Output
1 2 3 

The for loop runs three times, printing i each time before incrementing.

Example 2 (php)
<?php
  $fruits = ["apple", "banana", "cherry"];
  foreach ($fruits as $fruit) {
    echo $fruit . " ";
  }
?>
Output
apple banana cherry 

foreach visits each element of the array in order, without needing an index.

Key points

  • while checks its condition before running the loop body.
  • do-while always runs the loop body at least once.
  • for is ideal when the number of iterations is known in advance.
  • foreach is the simplest way to loop through arrays.
๐Ÿ’ก Note: Prefer foreach over for when looping through arrays โ€” it's clearer and avoids off-by-one index errors.

๐Ÿ“ Quick Quiz

1. Which loop always runs its body at least once?

2. Which loop is best suited for iterating over an array?

3. When is a for loop's condition checked?