A for each loop differs from a standard loop in that it requires some iterable expression and a variable assignment which will permit it to iterate the expression. For each loops were available from version 1.3.5 onwards.
YASS has an iterable expression that appears several times throughout the language - the list (but there are many other types such as the associative array). The iterable expression can also be a variable containing a list.
The first type of for each loop is the
for each...as loop:
for each([43, 99, 32, 84] as $value) print($value) end for
Or using a variable instead of a list:
$values = [43, 99, 32, 84] for each($values as $value) print($value) end for
A nice example that mimics Python in some ways is to use the
$values = [43, 99, 32, 84] $len = list_get_length($values) - 1 for each(range(0, $len) as $index) print($index, $values[$index]) end for
As of version 1.6.5 there is now the
for each...in loop as an alternative
for each...as loop.
$values = [43, 99, 32, 84] for each($value in $values) print($value) end for
$values = [43, 99, 32, 84] $len = list_get_length($values) - 1 for each($counter in range(0, $len)) print($counter, $values[$counter]) end for
ZPE 1.7.6 adds the
for each...break when loop syntax.
This is designed to terminate if the loop ever comes across an expression specified.
The following is an example of this:
$values = [43, 99, 32, 84] for each($value in $values break when $value is 32) print($value) end for
In this example, the loop will terminate when it gets a value of 32.
But the variable does not need to be limited to the one specified in the for loop. In fact, it can be any variable anywhere in the program.
$pos = 0 $values = [43, 99, 32, 84] for each($value in $values break when $pos is 2) print($value) print($pos++) end for
ZPE 1.8.4 (April 2020) improved the for each loop by making it handle generally iterable expressions more thoughtfully. This improvement meant that it is now possible for ZPE to handle many new types within the for each loop with little or no change.
ZPE 1.8.4 also added a new form of for each loop that produces two variables on each iteration when working with associative arrays:
$values = [1 => 100, 2 => 200, 3 => 300] for each($values as $key => $value) print($key & " : " & $value) end for
This is based entirely on the style of PHP which allows for keys to value pairs to be created.