foreach is a looping construct that executes a given piece of code for each element in a list/collection/array. In contrast to a for loop, the foreach loop doesn't require the coder to maintain a counter variable to avoid off-by-one (fencepost) bugs. It is recommended to use when simple iteration over whole array/list/collection is needed.
The foreach
statement repeats a group of embedded statements for each element in an array or object collection.
The foreach statement is used to iterate through the collection, but can not be used to add or remove items from the source collection, which could cause unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
Some form of the foreach loop is supported by most languages, though the syntax may differ greatly. Here are a few examples (to be extended):
foreach (var element in Collection)
for (SomeType element : collection)
for (element in collection)
for (element in iterable)
foreach($collection as $key => $value)
For Each Element As SomeType In Collection
...
Next
For Each Element In Group
...
Next
C++ (Since C++11)
for (auto i : collection )
Objective-C
for (id object in list)
for (item in list)
for (i in a)
for my $element (@array)
foreach stream as $var
The following languages do not natively support any kind of foreach statement:
For some languages, the foreach semantics are the basic form of a for
loop. Examples include
See also: loops, while-loop, for-loop, and do-while.