Syntax varies among languages. Most use the simple word for, although other use the more logical word foreach, roughly as follows:
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 Standard5 for for each .. in6 which pulls the value at each index.
It also supports for .. in7 which pulls the key at each index.
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
C int array as a collection of int (array size known at compile-time)
Most general: string or array as collection (collection size known at run-time)
In C#, assuming that myArray is an array of integers:
Language Integrated Query (LINQ) provides the following syntax, accepting a delegate or lambda expression:
C++11 provides a foreach loop. The syntax is similar to that of Java:
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.
Qt, a C++ framework, offers a macro providing foreach loops11 using the STL iterator interface:
Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:12
The C++/CLI language proposes a construct similar to C#.
Assuming that myArray is an array of integers:
Main article: ColdFusion Markup Language
CFML incorrectly identifies the value as "index" in this construct; the index variable does receive the actual value of the array element, not its index.
Common Lisp provides foreach ability either with the dolist macro:
or the powerful loop macro to iterate on more data types
and even with the mapcar function:
Main article: D (programming language)
or
Main article: Dart (programming language)
Main articles: 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):
13
Groovy supports for loops over collections like arrays, lists and ranges:
Groovy also supports a C-style for loop with an array index:
Collections in Groovy can also be iterated over using the each keyword and 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:
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.
Main article: Haxe
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",15 the "For-Each Loop",16 and the "foreach statement".1718: 264
Java also provides the stream api since java 8:19: 294–203
In ECMAScript 5, a callback-based forEach() method was added to the array prototype:20
The ECMAScript 6 standard introduced a more conventional for..of syntax that works on all iterables rather than operating on only array instances. However, no index variable is available with the syntax.
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's often useful to add a hasOwnProperty() test (or a hasOwn() test if supported).21
Alternatively, the Object.keys() method combined with the for..of loop can be used for a less verbose way to iterate over the keys of an object.22
Main article: Lua (programming language)
Source:23
Iterate only through numerical index values:
Iterate through all 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.
Main article: MATLAB
For each loops are supported in Mint, possessing the following syntax:
The for (;;) or while (true) infinite loop in Mint can be written using a for each loop and an infinitely long list.24
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.
NSArrays can also broadcast a message to their members:
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:
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:
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":
In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus:
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:
Main article: PHP syntax and semantics
It is also possible to extract both keys and values using the alternate syntax:
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 dictionaries:
As for ... in is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is...
... although using the enumerate function is considered more "Pythonic":
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...
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).
The for loop in its statement modifier form:
Direct modification of collection members with a doubly pointy block, <->:
Main article: Ruby (programming language)
This can also be used with a hash.
Main article: Rust (programming language)
The for loop has the structure for <pattern> in <expression> { /* optional statements */ }. It implicitly calls the 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 Iterators that returns the iterator unchanged. The loop calls the Iterator::next method on the iterator before executing the loop body. If Iterator::next returns Some(_), the value inside is assigned to the pattern and the loop body is executed; if it returns None, the loop is terminated.
Main article: Scala (programming language)
Main article: Scheme (programming language)
Main article: Smalltalk
Swift uses the for…in construct to iterate over members of a collection.25
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.
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:
Main article: Visual Basic (.NET)
or without type inference
Main articles: COMMAND.COM and cmd.exe
Invoke a hypothetical frob command three times, giving it a color name each time.
Main article: Windows PowerShell
From a pipeline
Main article: XSLT
26
"D Programming Language foreach Statement Documentation". Digital Mars. Retrieved 2008-08-04. http://www.digitalmars.com/d/statement.html#ForeachStatement ↩
"SWI-Prolog – foreach/2". Swi-prolog.org. Retrieved 2020-02-10. https://www.swi-prolog.org/pldoc/man?predicate=foreach/2 ↩
"Rebol". http://www.rebol.com/ ↩
"Red Programming Language". https://www.red-lang.org/ ↩
"Proposed ECMAScript 4th Edition – Language Overview" (PDF). Retrieved 2020-02-21. https://www.ecma-international.org/activities/Languages/Language%20overview.pdf ↩
"for each..in". Retrieved 2020-02-21. https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#for_each..in ↩
"for..in". Retrieved 2020-02-21. https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#for..in ↩
"C++11 Features in Visual C++ 11 - Visual C++ Team Blog - Site Home - MSDN Blogs". Blogs.msdn.com. 2011-09-12. Retrieved 2013-08-04. http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx ↩
"Range-based for loop (since C++11)". en.cppreference.com. Retrieved 2018-12-03. https://en.cppreference.com/w/cpp/language/range-for ↩
"std::for_each - cppreference". en.cppreference.com. Retrieved 2017-09-30. http://en.cppreference.com/w/cpp/algorithm/for_each ↩
"Qt 4.2: Generic Containers". Doc.qt.digia.com. Archived from the original on 2015-11-23. Retrieved 2013-08-04. https://web.archive.org/web/20151123090839/http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword ↩
Eric Niebler (2013-01-31). "Chapter 9. Boost.Foreach - 1.53.0". Boost.org. Retrieved 2013-08-04. http://www.boost.org/doc/libs/1_53_0/doc/html/foreach.html ↩
"Range Clause". The Go Programming Language Specification. The Go Programming Language. Retrieved October 20, 2013. https://golang.org/ref/spec#RangeClause ↩
"Enhanced for Loop - This new language construct[...]" "Java Programming Language, Section: Enhancements in JDK 5". Sun Microsystems, Inc. 2004. Retrieved 2009-05-26. http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html ↩
"The For-Each Loop" "The For-Each Loop". Sun Microsystems, Inc. 2008. Retrieved 2009-05-10. http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html ↩
"Implementing this interface allows an object to be the target of the "foreach" statement." "Iterable (Java Platform SE 6)". Sun Microsystems, Inc. 2004. Retrieved 2009-05-12. http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html ↩
Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991. 978-0134685991 ↩
"Array.prototype.forEach() - JavaScript | MDN". developer.mozilla.org. 2024-07-25. Retrieved 2024-12-03. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach ↩
"Object.hasOwn() - JavaScript | MDN". developer.mozilla.org. 2023-09-25. Retrieved 2024-12-03. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#description ↩
"Object.keys". Mozilla Developer Network. Retrieved May 7, 2014. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys ↩
"Lua Programming/Tables - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2017-12-06. https://en.wikibooks.org/wiki/Lua_Programming/Tables#Foreach_loop ↩
Chu, Oliver. "Mint Tutorial". Retrieved 20 October 2013. http://prezi.com/ougvv1wzx2lb/mint-tutorial-part-0/ ↩
"Control Flow — the Swift Programming Language (Swift 5.5)". https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_153 ↩
"XSLT Element". W3Schools.com. https://www.w3schools.com/xsl/xsl_for_each.asp ↩