In computer programming, foreach loop (or for-each loop) is a control flow statement for traversing items in a collection. is usually used in place of a standard loop statement. Unlike other loop constructs, however, loops[1] usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.
The statement in some languages has some defined order, processing each item in the collection from the first to the last.The statement in many other languages, especially array programming languages, does not have any particular order. This simplifies loop optimization in general and in particular allows vector processing of items in the collection concurrently.
Syntax varies among languages. Most use the simple word for
, roughly as follows:
for each item in collection: do something to item
Programming languages which support foreach loops include ABC, ActionScript, Ada, C++ (since C++11), C#, ColdFusion Markup Language (CFML), Cobra, D, Daplex (query language), Delphi, ECMAScript, Erlang, Java (since 1.5), JavaScript, Lua, Objective-C (since 2.0), ParaSail, Perl, PHP, Prolog,[2] Python, R, REALbasic, Rebol,[3] Red,[4] Ruby, Scala, Smalltalk, Swift, Tcl, tcsh, Unix shells, Visual Basic (.NET), and Windows PowerShell. Notable languages without foreach are C, and C++ pre-C++11.
ActionScript supports the ECMAScript 4.0 Standard[5] for for each .. in
[6] which pulls the value at each index.
for each (var value:int in foo)
// returns "1" then "2"
It also supports for .. in
[7] which pulls the key at each index.
// returns "apple" then "orange"
Ada supports foreach loops as part of the normal for loop. Say X is an array:
This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed.
Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...):
The C language does not have collections or a foreach construct. However, it has several standard data structures that can be used as collections, and foreach can be made easily with a macro.
However, two obvious problems occur:
C string as a collection of char
/* foreach macro viewing a string as a collection of char values */
char* ptrvar; \for (ptrvar = strvar; (*ptrvar) != '\0'; *ptrvar++)
int main(int argc, char** argv)
C int array as a collection of int (array size known at compile-time)
/* foreach macro viewing an array of int values as a collection of int values */
int* intpvar; \for (intpvar = intarr; intpvar < (intarr + (sizeof(intarr)/sizeof(intarr[0]))); ++intpvar)
int main(int argc, char** argv)
Most general: string or array as collection (collection size known at run-time)
can be removed and [[typeof]](col[0])
used in its place with GCC
/* foreach macro viewing an array of given type as a collection of values of given type */
idxtype* idxpvar; \for (idxpvar = col; idxpvar < (col + colsiz); ++idxpvar)
int main(int argc, char** argv)
In C#, assuming that myArray is an array of integers:
foreach (int x in myArray)
Language Integrated Query (LINQ) provides the following syntax, accepting a delegate or lambda expression:
myArray.ToList.ForEach(x => Console.WriteLine(x));
C++11 provides a foreach loop. The syntax is similar to that of Java:
int main
C++11 range-based for statements have been implemented in GNU Compiler Collection (GCC) (since version 4.6), Clang (since version 3.0) and Visual C++ 2012 (version 11 [8])
The range-based for
is syntactic sugar equivalent to:
The compiler uses argument-dependent lookup to resolve the begin
and end
functions.[9]
The C++ Standard Library also supports for_each
,[10] that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the start to the end, the range or direction can be changed by altering the first two parameters.
int main
Qt, a C++ framework, offers a macro providing foreach loops[11] using the STL iterator interface:
int main
Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:[12]
int main
The C++/CLI language proposes a construct similar to C#.
Assuming that myArray is an array of integers:
See main article: ColdFusion Markup Language.
// or
for (v in [1,2,3,4,5])
// or
// (Railo only; not supported in ColdFusion)letters = ["a","b","c","d","e"];letters.each(function(v));
// structsfor (k in collection)
// or
structEach(collection, function(k,v));
// or// (Railo only; not supported in ColdFusion)collection.each(function(k,v));
index
variable does receive the actual value of the array element, not its index.
Common Lisp provides foreach ability either with the dolist macro:
and even with the mapcar function:
See main article: D (programming language).
or
See main article: Dart (programming language).
See main article: Object Pascal and Delphi (software). Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section.
The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword across
.
In this example, every element of the structure my_list
is printed:
The local entity ic
is an instance of the library class ITERATION_CURSOR
. The cursor's feature item
provides access to each structure element. Descendants of class ITERATION_CURSOR
can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (my_list
in the example) are based on classes that inherit from the library class ITERABLE
.
The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword loop
is replaced by either all
(effecting universal quantification) or some
(effecting existential quantification).
This iteration is a boolean expression which is true if all items in my_list
have counts greater than three:
The following is true if at least one item has a count greater than three:
Go's foreach loop can be used to loop over an array, slice, string, map, or channel.
Using the two-value form gets the index/key (first element) and the value (second element):
Using the one-value form gets the index/key (first element):
Groovy supports for loops over collections like arrays, lists and ranges:
for (v in [1,2,3,4]) // loop over 4-element literal list
for (v in 1..4) // loop over the range 1..4
Groovy also supports a C-style for loop with an array index:
Collections in Groovy can also be iterated over using the each keywordand a closure. By default, the loop dummy is named it
Haskell allows looping over lists with monadic actions using mapM_
and forM_
(mapM_
with its arguments flipped) from Control.Monad:
code | prints | |
---|---|---|
1 2 3 4 | ||
tteesstt |
It's also possible to generalize those functions to work on applicative functors rather than monads and any data structure that is traversable using traverse
(for
with its arguments flipped) and mapM
(forM
with its arguments flipped) from Data.Traversable.
See main article: Haxe.
Lambda.iter(iterable, function(value) trace(value));
In Java, a foreach-construct was introduced in Java Development Kit (JDK) 1.5.0.[14]
Official sources use several names for the construct. It is referred to as the "Enhanced for Loop",[14] the "For-Each Loop",[15] and the "foreach statement".[16] [17]
Java also provides the stream api since java 8:[18]
The ECMAScript 6 standard has [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of for..of]
for index-less iteration over generators, arrays and more:
Alternatively, function-based style: [19]
For unordered iteration over the keys in an Object, JavaScript features the for...in
loop:
To limit the iteration to the object's own properties, excluding those inherited through the prototype chain, it is sometimes useful to add a hasOwnProperty test, if supported by the JavaScript engine (for WebKit/Safari, this means "in version 3 or later").
ECMAScript 5 provided Object.keys method, to transfer the own keys of an object into array.[20]
See main article: Lua (programming language). Source:[21]
Iterate only through numerical index values:
In Mathematica, Do
will simply evaluate an expression for each element of a list, without returning any value.
It is more common to use Table
, which returns the result of each evaluation in a new list.
In[]:= Table[item^2, {item, list}]Out[]=
See main article: MATLAB.
For each loops are supported in Mint, possessing the following syntax:
The for (;;)
or while (true)
infinite loopin Mint can be written using a for each loop and an infinitely long list.[22]
Foreach loops, called Fast enumeration, are supported starting in Objective-C 2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc.
for(id obj in a)
NSArrays can also broadcast a message to their members:
[a makeObjectsPerformSelector:@selector(printDescription)]
Where blocks are available, an NSArray can automatically perform a block on every contained item:
The type of collection being iterated will dictate the item returned with each iteration.For example:
for(id key in d)
OCaml is a functional programming language. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.
For lists:
or in short way:
For arrays:
or in short way:
The ParaSail parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:
ParaSail also supports filters on iterators, and the ability to refer to both the key and the value of a map. Here is a forward iteration over the elements of "My_Map" selecting only elements where the keys are in "My_Set":
for each [Str => Tr] of My_Map forward loop // ... do something with Str or Trend loop
In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus:
for elt in eltset do
In Perl, foreach (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable.
List literal example:
Array examples:
Hash example:
Direct modification of collection members:
See main article: PHP syntax and semantics.
It is also possible to extract both keys and values using the alternate syntax:
Direct modification of collection members:
// also works with the full syntaxforeach ($arr as $key => &$value)
See main article: Python (programming language).
Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in associative arrays:
As for ... in
is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is...
... though using the enumerate
function is considered more "Pythonic":
See main article: R (programming language).
As for ... in
is the only kind of for
loop in R, the equivalent to the "counter" loop found in other languages is...
See main article: Racket (programming language).
or using the conventional Scheme for-each
function:
do-something-with
is a one-argument function.
In Raku, a sister language to Perl, for must be used to traverse elements of a list (foreach is not allowed). The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s).
List literal example:
Array examples:
The for loop in its statement modifier form:
Hash example:
or
or
Direct modification of collection members with a doubly pointy block, <->:
See main article: Ruby (programming language).
or
This can also be used with a hash.
See main article: Rust (programming language). The for
loop has the structure IntoIterator::into_iter
method on the expression, and uses the resulting value, which must implement the Iterator
trait. If the expression is itself an iterator, it is used directly by the for
loop through an implementation of IntoIterator
for all Iterator
s that returns the iterator unchanged. The loop calls the Iterator::next
method on the iterator before executing the loop body. If Iterator::next
returns [[option type|Some(_)]]
, the value inside is assigned to the pattern and the loop body is executed; if it returns None
, the loop is terminated.
// Immutable reference:for number in &numbers
for square in numbers.iter.map(|x| x * x)
// Mutable reference:for number in &mut numbers
// prints "[2, 4, 6]":println!("", numbers);
// Consumes the Vec and creates an Iterator:for number in numbers
// Errors with "borrow of moved value":// println!("", numbers);
See main article: Scala (programming language).
for yield doSomething(x)for yield multiplyByTwo(x)
// return nothing, just perform actionitems foreach items foreach println
for doSomething(x)for println(x)
// pattern matching example in for-comprehensionfor ((key, value) <- someMap) println(s"$key -> $value")
See main article: Scheme (programming language). do-something-with
is a one-argument function.
See main article: Smalltalk.
Swift uses the for
…in
construct to iterate over members of a collection.[23]
The for
…in
loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times.
for i in 0...10
SystemVerilog supports iteration over any vector or array type of any dimensionality using the foreach
keyword.
A trivial example iterates over an array of integers:
A more complex example iterates over an associative array of arrays of integers:
Tcl uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list.
It is also possible to iterate over more than one list simultaneously. In the following i
assumes sequential values of the first list, j
sequential values of the second list:
See main article: Visual Basic (.NET).
or without type inference
See main article: COMMAND.COM and cmd.exe. Invoke a hypothetical frob
command three times, giving it a color name each time.
See main article: Windows PowerShell.
From a pipeline
$list | foreach $list | %
foreach
Statement Documentation. 2008-08-04. Digital Mars.