Foreach
Encyclopedia
For each is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for
statement
. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one error
s and makes code simpler to read. In object-oriented languages an iterator
, even if implicit, is often used as the means of traversal.
for each item in collection:
do something to item
, Ada
, C++11, C#, Cobra
, D
, ECMAScript
, Java
(since 1.5), JavaScript
, Objective-C
(since 2.0), Perl
, PHP
, Python
, REALbasic
, Ruby
, Smalltalk
, Tcl
, tcsh
, Daplex
(a query language), Unix shell
s, Visual Basic .NET
and Windows PowerShell
. Notable languages without foreach are C
and C++
(prior to C++11).
ActionScript
ActionScript supports foreach loops by key/index and by value:
Note: someArray could be any object and someObject could be an array, but typical usage is as shown.
Ada
Ada supports foreach loops as part of the normal for loop
. Say X is an array:
Note: This syntax is mostly used on arrays but will also work with other types when a full iteration is needed.
C++
C++11 provides a for each loop. The syntax is taken from Java and looks like this:
Currently, C++11 range-based for statements have been implemented in GCC
(since version 4.6) and clang
(since version 3.0).
Qt, a C++ framework, offers a macro providing foreach loops using the STL iterator interface:
Objective-C
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:
D
Delphi
Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section.
Eiffel
The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword
In this example, every element of the structure
across my_list as ic loop print (ic.item) end
The local entity
The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword
) or
).
This iteration is a boolean expression which is true if all items in
across my_list as ic all ic.item.count > 3 end
The following is true if at least one item has a count greater than three:
across my_list as ic some ic.item.count > 3 end
Go
Go's foreach loop can be used to loop over an array, slice, string, map, or channel.
Using the two-value form, we get the index/key (first element) and the value (second element):
Using the one-value form, we get the index/key (first element):
http://golang.org/doc/go_spec.html#RangeClause
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
haXe
Java
A foreach-construct was introduced in JDK 1.5.0.
Official sources use several names for the construct. It is referred to as the "Enhanced for Loop" the "For-Each Loop" and the "foreach statement".
JavaScript
For iterating over Array objects, JavaScript 1.6 (ECMA-262 Edition 5) offers a forEach method.
Importantly, Microsoft Internet Explorer prior to version 9 does not natively support this method (or any of several other Array object iteration methods introduced after JavaScript 1.5); for information on implementing these methods for backwards compatibility, see the Mozilla Developer Center: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach.
For unordered iteration over the keys in an Object, JavaScript features the
In order to limit the iteration to the object's own properties, excluding the ones 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").
Gecko’s JavaScript engine also has a
Also note that it is inadvisable to use either a
For Lists :
or in short way :
For Arrays :
or in short way :
Pascal
The ISO 10206:1990 standard introduced iteration over set types in Pascal:
Perl
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:
PHP
PHP has an idiosyncratic syntax:
It is also possible to extract both keys and values using the alternate syntax:
Direct modification of collection members:
Python
Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in associative arrays:
As
... though using the
Ruby
or
or using the conventional Scheme
Smalltalk
Tcl
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. The code below prints:
1 2
3 4
5 6
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:
This prints:
1 a
2 b
3 c
Visual Basic .NET
XSL
<!-- do something for the elements in <set> -->
For loop
In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement....
statement
Statement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...
. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one error
Off-by-one error
An off-by-one error is a logical error involving the discrete equivalent of a boundary condition. It often occurs in computer programming when an iterative loop iterates one time too many or too few...
s and makes code simpler to read. In object-oriented languages an iterator
Iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container. Various types of iterators are often provided via a container's interface...
, even if implicit, is often used as the means of traversal.
Syntax
Syntax varies among languages. Most use the simple wordfor
, roughly as follows:for each item in collection:
do something to item
Language support
Some of the languages with support for foreach loops include ABC, ActionScriptActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...
, Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
, C++11, C#, Cobra
Cobra (programming language from Cobra Language LLC)
Cobra is an object-oriented programming language produced by Cobra Language LLC. Cobra is designed by Chuck Esterbrook, and runs on the Microsoft .NET and Mono platforms. It is strongly influenced by Python, C#, Eiffel, Objective-C, and other programming languages. It supports both static and...
, D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...
, ECMAScript
ECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...
, Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
(since 1.5), JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
, Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...
(since 2.0), Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, REALbasic
REALbasic
Realbasic is the object-oriented dialect of the BASIC programming language used in Real Studio, a programming environment, developed and commercially marketed by Real Software, Inc of Austin, Texas for Mac OS X, Microsoft Windows, 32-bit x86 Linux and the web.- Language features :RB is a strongly...
, Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
, Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...
, tcsh
Tcsh
tcsh is a Unix shell based on and compatible with the C shell . It is essentially the C shell with programmable command line completion, command-line editing, and a few other features.-History:...
, Daplex
Daplex
Daplex is an old computer language used for creating distributed database systems and can be used as a global query language.-Example of Daplex Local Schemata:Type EMPLOYEE is entityName: stringSSN: integerADDRESS: stringSALARY: Floatend entity;...
(a query language), Unix shell
Unix shell
A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems...
s, Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...
and Windows PowerShell
Windows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...
. Notable languages without foreach are C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
and C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
(prior to C++11).
ActionScriptActionScriptActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...
ActionScript supports foreach loops by key/index and by value:Note: someArray could be any object and someObject could be an array, but typical usage is as shown.
AdaAda (programming language)Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
Ada supports foreach loops as part of the normal for loopFor loop
In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement....
. Say X is an array:
Note: This syntax is mostly used on arrays but will also work with other types when a full iteration is needed.
C#
Assuming that myArray is an array of integers:C++C++C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
C++11 provides a for each loop. The syntax is taken from Java and looks like this:Currently, C++11 range-based for statements have been implemented in GCC
GNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...
(since version 4.6) and clang
Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages. It uses the Low Level Virtual Machine as its back end, and Clang has been part of LLVM releases since LLVM 2.6....
(since version 3.0).
Qt, a C++ framework, offers a macro providing foreach loops using the STL iterator interface:
Objective-CObjective-CObjective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...
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
Blocks (C language extension)
Blocks are a nonstandard extension added by Apple Inc. to the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages...
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:
DD (programming language)The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...
DelphiObject PascalObject Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...
Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section. EiffelEiffel (programming language)Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...
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:across my_list as ic loop print (ic.item) end
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 quantificationUniversal quantification
In predicate logic, universal quantification formalizes the notion that something is true for everything, or every relevant thing....
) or
some
(effecting existential quantificationExistential quantification
In predicate logic, an existential quantification is the predication of a property or relation to at least one member of the domain. It is denoted by the logical operator symbol ∃ , which is called the existential quantifier...
).
This iteration is a boolean expression which is true if all items in
my_list
have counts greater than three:across my_list as ic all ic.item.count > 3 end
The following is true if at least one item has a count greater than three:
across my_list as ic some ic.item.count > 3 end
GoGo (programming language)Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being...
Go's foreach loop can be used to loop over an array, slice, string, map, or channel.Using the two-value form, we get the index/key (first element) and the value (second element):
for index, value := range someCollection {
// do something to index and value
}
Using the one-value form, we get the index/key (first element):
for index := range someCollection {
// do something to index
}
http://golang.org/doc/go_spec.html#RangeClause
Groovy
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
HaskellHaskell (programming language)Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...
haXeHaXehaXe is a versatile open-source high-level multiplatform programming language described on its website as a "universal language".It can produce:* Flash applications and games* Multi-platform client-side web applications* Apache CGI web applications...
JavaJava (programming language)Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
A foreach-construct was introduced in JDK 1.5.0.Official sources use several names for the construct. It is referred to as the "Enhanced for Loop" the "For-Each Loop" and the "foreach statement".
JavaScriptJavaScriptJavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
For iterating over Array objects, JavaScript 1.6 (ECMA-262 Edition 5) offers a forEach method.Importantly, Microsoft Internet Explorer prior to version 9 does not natively support this method (or any of several other Array object iteration methods introduced after JavaScript 1.5); for information on implementing these methods for backwards compatibility, see the Mozilla Developer Center: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach.
For unordered iteration over the keys in an Object, JavaScript features the
for...in
loop:In order to limit the iteration to the object's own properties, excluding the ones 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").
Gecko’s JavaScript engine also has a
for each...in
statement, which iterates over the values in the object, not the keys.Also note that it is inadvisable to use either a
for...in
or for each...in
statement on an Array object in JavaScript, due to the above issue of properties inherited from prototypes, and also because it only iterates over existent keys and is not guaranteed to iterate over the elements in any particular order. A regular C-style for loop should be used instead.Ocaml
Since Ocaml is a functional language, 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 :
PascalPascal (programming language)Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
The ISO 10206:1990 standard introduced iteration over set types in Pascal: PerlPerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
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:
PHPPHPPHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
PHP has an idiosyncratic syntax:It is also possible to extract both keys and values using the alternate syntax:
Direct modification of collection members:
PythonPython (programming language)Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
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": RubyRuby (programming language)Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
or
You can also use this with a hash.
Racket
or using the conventional Scheme
for-each
function: SmalltalkSmalltalkSmalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
TclTclTcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...
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. The code below prints:1 2
3 4
5 6
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:
This prints:
1 a
2 b
3 c
Visual Basic .NETVisual Basic .NETVisual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...
XSLXSLThe three-letter abbreviation XSL may have multiple meanings, as described below:* In computing, the Extensible Stylesheet Language: a set of language technologies for defining XML document transformation and presentation* XSL Formatting Objects...
<!-- do something for the elements in <set> -->