Loops

for/while/do-while/foreach patterns you’ll use in backend code.

On this page

for Loop

for is ideal when you have a known range (like paging or index-based iteration). Keep the loop body small and readable.

<?php
for ($i = 1; $i <= 5; $i++) {
  echo $i . PHP_EOL;
}

while Loop

while repeats while a condition is true. It is useful when the number of iterations is not fixed.

<?php
$attempts = 0;

while ($attempts < 3) {
  $attempts++;
  echo 'Attempt: ' . $attempts . PHP_EOL;
}

do-while Loop

do-while always runs the body at least once. Use it when you must perform an action before checking a condition.

<?php
$number = 0;

do {
  $number++;
  echo $number . PHP_EOL;
} while ($number < 3);

foreach (Most Common in PHP)

foreach is the go-to loop for arrays. It is readable and less error-prone than index-based loops.

<?php
$tags = ['php', 'mysql', 'security'];

foreach ($tags as $tag) {
  echo $tag . PHP_EOL;
}

foreach with Key and Value

Associative arrays often need both key and value.

<?php
$user = ['id' => 1, 'name' => 'Ozan'];

foreach ($user as $key => $value) {
  echo $key . ': ' . $value . PHP_EOL;
}

Production Tip

If you loop over database results, fetch in a safe way (PDO) and keep the loop body focused. Avoid expensive work inside loops unless necessary.