For each

foreach is the loop you use when you want to iterate through arrays or object properties without managing indexes manually.

1) Basic Indexed Array

foreach ($colors as $value) {
    echo $value;
}

You get each value directly. No need for $i++, no need to check bounds.


2) Associative Arrays (key + value)

foreach ($members as $key => $value) {
    echo "$key: $value";
}

Useful for things like:

  • MemberPress subscription arrays
  • Pretty Links meta data
  • WordPress options arrays (get_option() output)

3) Foreach on Objects

Properties get exposed like associative arrays:

foreach ($myCar as $prop => $value) {
    echo "$prop: $value";
}

4) break in foreach

Stops the loop immediately.

foreach ($colors as $x) {
    if ($x === "blue") break;
}

5) continue in foreach

Skips one iteration and moves to the next.

foreach ($colors as $x) {
    if ($x === "blue") continue;
}

6) By-reference (&)

This one is important because it changes the original array.

foreach ($statuses as &$x) {
    if ($x === "trial") {
        $x = "pending";
    }
}
unset($x); // ← always do this afterward!

If you don’t use &, modifications affect only the temporary $x, not the array.

If you do use &, your array is changed permanently — useful for bulk editing or normalization.

But if you forget unset($x);, the last referenced value leaks and can mutate the array later by accident.


7) Alternative Syntax

Good for templates, especially inside WordPress:

foreach ($colors as $x) :
    echo $x;
endforeach;