Foreach loop
Foreach loop is a control flow statement for traversing items in a collection. Foreach is usually used in place of a standard for loop 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 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 foreach statement in some languages has some defined order, processing each item in the collection from the first to the last.
The foreach 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
Syntax varies among languages. Most use the simple wordfor
, roughly as follows:for each item in collection:
do something to item
Language support
s which support foreach loops include ABC, ActionScript, Ada, C++11, C#, ColdFusion Markup Language, Cobra, D, Daplex, Delphi, ECMAScript, Erlang, Java, JavaScript, Lua, Objective-C, ParaSail, Perl, PHP, Prolog, Python, REALbasic, 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 3.0
supports the ECMAScript 4.0 Standard forfor each.. in
which pulls the value at each index.var foo:Object = ;
for each
// returns "1" then "2"
It also supports
for.. in
which pulls the key at each index.for
// returns "apple" then "orange"
Ada
supports foreach loops as part of the normal for loop. Say X is an array:for I in X'Range loop
X := Get_Next_Element;
end loop;
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 :
for Obj of X loop
-- Work on Obj
end loop;
C
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:
- The macro is unhygienic: it declares a new variable in the existing scope which remains after the loop.
- One foreach macro cannot be defined that works with different collection types or that is extensible to user types.
- include
- define foreach \
for
int main
C int array as a collection of int
- include
- define foreach \
for /sizeof)); ++intpvar)
int main
Most general: string or array as collection
- include
- include
- define arraylen /sizeof)
- define foreach \
for
int main
C#
In C#, assuming that myArray is an array of integers:foreach
Language Integrated Query provides the following syntax, accepting a delegate or lambda expression:
myArray.ToList.ForEach;
C++
provides a foreach loop. The syntax is similar to that of Java:- include
C++11 range-based for statements have been implemented in GNU Compiler Collection , Clang and Visual C++ 2012
The range-based for is syntactic sugar equivalent to:
for ; __anon != end
The compiler uses argument-dependent lookup to resolve the begin and end functions.
The C++ Standard Library also supports for_each, 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 beginning to the end, the range and direction you can change the direction or range by altering the first two parameters.
- include
- include
// contains std::for_each - include
Qt, a C++ framework, offers a macro providing foreach loops using the STL iterator interface:
- include
- include
Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:
- include
- include
C++/CLI
The C++/CLI language proposes a construct similar to C#.Assuming that myArray is an array of integers:
for each
ColdFusion Markup Language (CFML)
Script syntax
// arrays
arrayeach;
// or
for
// or
//
letters = ;
letters.each;
// structs
for
// or
structEach;
// or
//
collection.each;
Tag syntax
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
do )
and even with the mapcar function:
D
foreach
or
foreach
Dart
for
Object Pascal, Delphi
Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section.for enumerator in collection do
begin
//do something here
end;
Eiffel
The iteration form of the Eiffel loop construct is introduced by the keywordacross
.In this example, every element of the structure
my_list
is printed:across my_list as ic loop print 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 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
or some
.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
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 and the value :
for index, value := range someCollection
Using the one-value form, we get the index/key :
for index := range someCollection
Groovy
supports for loops over collections like arrays, lists and ranges:def x =
for // loop over the 4-element array x
for // loop over 4-element literal list
for // loop over the range 1..4
Groovy also supports a C-style for loop with an array index:
for
Collections in Groovy can also be iterated over using the each keyword
and a closure. By default, the loop dummy is named it
x.each // print every element of the x array
x.each // equivalent to line above, only loop dummy explicitly named "i"
Haskell
allows looping over lists with monadic actions usingmapM_
and forM_
from :code | prints |
mapM_ print | 1 2 3 4 |
forM_ "test" $ \char -> do putChar char putChar char | 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
and mapM
from .Haxe
for
Lambda.iter trace);
Java
In Java, a foreach-construct was introduced in Java Development Kit 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".
for
JavaScript
The EcmaScript 6 standard has
for index-less iteration over generators, arrays and more:for
Alternatively, function-based style:
array.forEach
For unordered iteration over the keys in an Object, JavaScript features the
for...in
loop:for
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
ECMAScript 5 provided Object.keys method, to transfer the own keys of an object into array.
var book = ;
for
Lua
Iterate only through numerical index values:for index, value in ipairs do
-- do something
end
for index, value in pairs do
-- do something
end
Mathematica
In Mathematica,Do
will simply evaluate an expression for each element of a list, without returning any value.In:= Do
It is more common to use
Table
, which returns the result of each evaluation in a new list.In:= list = ;
In:= Table
Out=
MATLAB
for item = array
%do something
end
Mint
For each loops are supported in Mint, possessing the following syntax:for each element of list
/* 'Do something.' */
end
The
for
or while
infinite loopin Mint can be written using a for each loop and an infinitely long list.
import type
/* 'This function is mapped to'
* 'each index number i of the'
* 'infinitely long list.'
*/
sub identity
return x
end
/* 'The following creates the list'
* ''
*/
infiniteList = list
for each element of infiniteList
/* 'Do something forever.' */
end
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, NSSet, etc.NSArray *a = ; // Any container class can be substituted
for
NSArrays can also broadcast a message to their members:
NSArray *a = ;
;
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:
NSDictionary *d = ;
for
OCaml
is a functional language. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.For lists:
List.iter ;;
or in short way:
List.iter print_int ;;
For arrays:
Array.iter ;;
or in short way:
Array.iter print_int ;;
ParaSail
The ParaSail parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:var Con : Container
//...
for each Elem of Con concurrent loop // loop may also be "forward" or "reverse" or unordered
//... do something with Elem
end loop
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":
var My_Map : Map
const My_Set : Set
for each of My_Map forward loop
//... do something with Str or Tr
end loop
Pascal
In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus:var
elt: ElementType;
eltset: set of ElementType;
for elt in eltset do
Perl
In Perl, foreach 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:
foreach
Array examples:
foreach
foreach $x
Hash example:
foreach $x
Direct modification of collection members:
@arr = ;
foreach $x
- Now @arr = ;
PHP
foreach
It is also possible to extract both keys and values using the alternate syntax:
foreach
Direct modification of collection members:
$arr = array;
foreach
// Now $arr = array;
// also works with the full syntax
foreach
-
Python
for item in iterable_collection:
# Do something with item
Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on pairs in associative arrays:
for key, value in some_dict.items: # Direct iteration on a dict iterates on its keys
# Do stuff
As
for... in
is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is...for i in range:
# Do something to seq
... though using the
enumerate
function is considered more "Pythonic":for i, item in enumerate:
# Do stuff with item
# Possibly assign it back to seq
Racket
)
or using the conventional Scheme
for-each
function:do-something-with
is a one-argument function.Raku
In Raku, a sister language to Perl, for must be used to traverse elements of a list. 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.List literal example:
for 1..4
Array examples:
for @arr
The for loop in its statement modifier form:
.say for @arr;
for @arr -> $x
for @arr -> $x, $y
Hash example:
for keys %hash -> $key
or
for %hash.kv -> $key, $value
or
for %hash -> $x
Direct modification of collection members with a doubly pointy block, <->:
my @arr = 1,2,3;
for @arr <-> $x
- Now @arr = 2,4,6;
Ruby
set.each do |item|
# do something to item
end
or
for item in set
# do something to item
end
This can also be used with a hash.
set.each do |item,value|
# do something to item
# do something to value
end
Rust
let mut numbers = vec!;
// Immutable reference:
for number in numbers.iter
// Mutable reference:
for number in numbers.iter_mut
// prints "":
println!;
// Consumes the Vec and creates an Iterator:
for number in numbers
// Errors with "borrow of moved value":
// println!;
Scala
// return list of modified elements
items map
items map multiplyByTwo
for yield doSomething
for yield multiplyByTwo
// return nothing, just perform action
items foreach
items foreach println
for doSomething
for println
Scheme
do-something-with
is a one-argument function.Smalltalk
collection do:
Swift
uses thefor
…in
construct to iterate over members of a collection.for thing in someCollection
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
for i in 0...10
SystemVerilog
supports iteration over any vector or array type of any dimensionality using theforeach
keyword.A trivial example iterates over an array of integers:
code | prints |
int array_1d = '; foreach array_1d $display; | array_1d: 3 array_1d: 2 array_1d: 1 array_1d: 0 |
A more complex example iterates over an associative array of arrays of integers:
code | prints |
int array_2d = '; foreach array_2d $display; | array_2d: 10 array_2d: 11 array_2d: 20 array_2d: 21 |
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.code | prints |
foreach | 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:code | prints |
foreach i j | 1 a 2 b 3 c |
Visual Basic .NET
For Each item In enumerable
' Do something with item.
Next
or without type inference
For Each item As type In enumerable
' Do something with item.
Next
Windows
Conventional command processor
Invoke a hypotheticalfrob
command three times, giving it a color name each time.C:\>FOR %%a IN DO frob %%a
Windows PowerShell
foreach
From a pipeline
$list | ForEach-Object
- or using the aliases
$list | %