Skip to main content

foreach

Discworld LPC help

foreach

Name

foreach() - iterate through an array or mapping

Synopsis

foreach(value in array) {
statements;
...;
}
foreach(key, value in mapping) {
statements;
...;
}

Description

foreach() provides an easy way to iterate through an array or mapping and can be used where you used to use a for() or while() loop. It works on both arrays and mappings, provided that the keys of the mapping are all of the same type. Otherwise it will fail. If the array or the mapping are coming from an expression rather then a variable it is evaluated only once. This means that you can modify the mapping or array you are handling in the foreach loop itself without running into problems. Just like in for() and while() loops, a 'break' in the body of the loop will terminate it, and a 'continue' will continue the execution from the beginning of the loop, after taking the next value from the array or mapping.

Examples

foreach (elem in arr) {
printf("Elem = %d\n", elem);
}
foreach (name, value in mapp) {
printf("Key: %s, Value: %d\n", name, value);
}

See also

for, while