PHPLesson 8 of 13

Loops

Loops run the same code many times. A for loop counts from one number to another, a while loop repeats while a condition stays true, and foreach walks through every item of an array. Together they remove almost all repetitive typing from your code.

Loops run the same code many times. A for loop counts from one number to another, a while loop repeats while a condition stays true, and foreach walks through every item of an array. Together they remove almost all repetitive typing from your code.

The for loop has three parts in its header: where to start, when to stop, and how to step. for ($i = 0; $i < 5; $i++) runs five times with $i holding 0, 1, 2, 3, 4. The middle part is the condition that ends the loop.

The while loop only needs a condition. while ($count > 0) keeps running until the condition turns false. It is the right choice when you do not know in advance how many times to repeat, like draining a queue or reading until the end of a file.

foreach is the one you will use most with data. It takes every value out of an array, one at a time, and hands it to your code. With associative arrays it can also hand you the key. break stops a loop early, and continue skips to the next round.

Foreach with keys

The key => value form of foreach works on any array. With an associative array the key is the name, and with an indexed array it is the number. You read both sides without touching the array index yourself.

PHP
$user = ["name" => "Aya", "age" => 24];
foreach ($user as $key => $value) {
  echo "$key: $value<br>";
}
// name: Aya
// age: 24

break and continue

break ends the loop entirely and jumps past it. continue skips the rest of the current round and starts the next one. They keep loops short by handling special cases in the middle.

PHP
for ($i = 1; $i <= 10; $i++) {
  if ($i % 2 === 0) continue;  // skip even numbers
  if ($i === 7) break;         // stop at 7
  echo $i . " ";               // 1 3 5
}

Syntax

PHP
<?php
for ($i = 1; $i <= 3; $i++) {
  echo $i . "\n";
}
?>

foreach Copies Value, Not Reference

foreach ($arr as $v) copies — changing $v doesn't change array. Use &$v to modify.

PHP
foreach ($arr as &$v) $v *=2;

Good to know

  • for counts from a start to a stop with a step.
  • while repeats while its condition is true.
  • foreach hands you every array item, with the key if you ask.
  • break exits the loop; continue skips one round.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground