For in PHP

PHP provides several ways to create loops. Let’s explore the different types of loops available.

<?php

// The most basic type, with a single condition.
$i = 1;
while ($i <= 3) {
    echo $i . "\n";
    $i = $i + 1;
}

// A classic initial/condition/after for loop.
for ($j = 0; $j < 3; $j++) {
    echo $j . "\n";
}

// PHP doesn't have a direct equivalent to Go's "range" over integers,
// but we can achieve similar functionality with a for loop.
for ($i = 0; $i < 3; $i++) {
    echo "range " . $i . "\n";
}

// A loop without a condition will run indefinitely until you break out of it.
while (true) {
    echo "loop\n";
    break;
}

// You can also continue to the next iteration of the loop.
foreach (range(0, 5) as $n) {
    if ($n % 2 == 0) {
        continue;
    }
    echo $n . "\n";
}

When you run this PHP script, you’ll get the following output:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In PHP, we have several loop constructs:

  1. while loop: Executes a block of code as long as the specified condition is true.
  2. for loop: A compact way to write a loop that includes initialization, condition, and increment/decrement.
  3. foreach loop: Used to iterate over arrays and objects.
  4. do-while loop: Similar to the while loop, but it executes the code block once before checking the condition.

PHP doesn’t have a direct equivalent to Go’s range over integers, but we can achieve similar functionality using foreach with range() function or a regular for loop.

The break statement can be used to exit a loop prematurely, and the continue statement skips the rest of the current iteration and continues with the next one.

We’ll see other loop forms later when we look at arrays, iterators, and other data structures.