Skip to content
On this page

Statements: Foreach

The foreach statement is used to iterate over any iterable value.

syntax
ForeachStatement :
  foreach (Iterator | ( ( Iterator ) ) ) BlockStatement (else BlockStatement)?
 
Iterator :
  Expression as Variable (=> Variable)?


foreach $iterable as $value {
    // ...
}

You can also use the => operator to access the key and value of an associative iterable.

foreach $iterable as $key => $value {
    // ...
}

Foreach loops can also contain an else block that is executed if the iterable is empty.

foreach $iterable as $value {
    // ...
} else {
    // $iterable is empty
}

Licensed under either of the MIT License or the Apache License (Version 2.0), at your option.