A foreach loop is available implictly in many programming languages (including
Perl,
LPC and
C#) and created using consutrcts such as
for loops in other languages.
Generally speaking, a foreach loop iterates over each member of an array or list, performing an operation or series of operations on each element in this data structure. Here are some examples -
Perl -
foreach (@listofStrings) {
print $_;
}
die "Done.";
Note that Perl takes every element of the list and puts it into the special variable $_.
LPC -
string *carp = ({"foo", "bar"});
foreach ( object koi in carp ) {
write(koi);
}
LPC demands that you specify a variable to put each element of the array into. In the above example, the object variable koi only has a scope of the foreach loop.
The benefits of this construct should be fairly clear. It can be used to perform an action on every part of a linear array or list, and can be used to perform an action on every member of an associative array by foreach()ing the keys to this structure.