foreach

foreach() loops can be used to iterate over the elements of an array or mapping . The array form is:

foreach (<var> in <expr>) {
    ...
}

Where <expr> is any expression that returns an array. For example,

int x;
foreach (x in ({ 1, 2, 3, 4 })) {
    printf("%i ", x);
}

is exactly the same as doing:

int x, i, n;
int *y = ({ 1, 2, 3, 4 })
n = sizeof(y);
for (i = 0; i < n; i++) {
    x = y[i];
    printf("%i ", x);
}

Note that <expr> is only evaluated once, at the start of the loop. The usual loop commands, like break and continue , work within foreach loops as well.

The second form is used to iterate over a mapping :

foreach (<var>, <var> in <expr>) {
    ...
}

Each time through the loop, the first var is set to a key from the mapping , and the second is set to the corresponding value, so:

int x, y;
foreach (x, y in ([ 1 : 2, 3 : 4, 5 : 6 ]) ) {
    printf("%i : %i\n", x, y);
}

is the same as the considerably more complex:

int x, y;
mapping m = ([ 1 : 2, 3 : 4, 5 : 6 ]);
int *k = keys(m);
int n = sizeof(k);
for (int i = 0; i < n; i++) {
    x = k[i];
    y = m[x];
    printf("%i : %i\n", x, y);
}    

See also the summary of loops .


Tim Hollebeek

Beek @ZorkMUD, Lima Bean, IdeaExchange, TMI-2, and elsewhere