PHP Loops

while Loop

Runs while the condition is true

Basic Structure:

while (condition) {
    // code block
}

Example

$i = 1;
while ($i <= 5) {
  echo $i . " ";
  $i++;
}

do...while Loop

Runs once before checking the condition

Basic Structure:

do {
    // code block
} while (condition);

Example

$i = 1;
do {
  echo $i . " ";
  $i++;
} while ($i <= 5);

for Loop

Good when the number of iterations is known

Basic Structure:

for (initialization; condition; update) {
    // code block
}

Example

for ($i = 0; $i < 5; $i++) {
  echo $i . " ";
}

foreach Loop

The foreach loop is a special loop used to iterate over arrays and collections in PHP. It automatically goes through each element in the array without needing to manage a counter manually.

It's ideal when working with lists or associative arrays, as it gives direct access to the elements (and optionally keys) of the array.

Basic Usage:

Iterate through a simple indexed array

Loading...
Output:

This loop goes through each value in the $colors array and stores it in $color, which is used in the loop body.

Accessing Keys and Values:

Iterate through an associative array to get both keys and values

Loading...
Output:

Here, $name gets the key (like "Alice") and $age gets the value (like 25) during each iteration.

Best Practice: Use foreach when you want to go through every item in an array without modifying the array index manually.

break and continue

break exits the loop immediately:

for ($i = 0; $i < 10; $i++) {
  if ($i == 5) break;
  echo $i . " ";
}

continue skips to the next iteration:

for ($i = 0; $i < 5; $i++) {
  if ($i == 2) continue;
  echo $i . " ";
}

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic