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 word for, 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 for for 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:
C string as a collection of char

  1. include
/* foreach macro viewing a string as a collection of char values */
  1. define foreach \
char* ptrvar; \
for
int main

C int array as a collection of int

  1. include
/* foreach macro viewing an array of int values as a collection of int values */
  1. define foreach \
int* intpvar; \
for /sizeof)); ++intpvar)
int main

Most general: string or array as collection

  1. include
  2. include
/* foreach macro viewing an array of given type as a collection of values of given type */
  1. define arraylen /sizeof)
  2. define foreach \
idxtype* idxpvar; \
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:

  1. include
int main

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.

  1. include
  2. include // contains std::for_each
  3. include
int main

Qt, a C++ framework, offers a macro providing foreach loops using the STL iterator interface:

  1. include
  2. include
int main

Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:

  1. include
  2. include
int main

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



#v#


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.


#collection#

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 keyword across.
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 using mapM_ and forM_ from :
codeprints


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
Iterate through all index values:
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 loop
in 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 Univ_String, Value_Type => Tree> :=...
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
  1. 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


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
  1. 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 the forin construct to iterate over members of a collection.

for thing in someCollection

The forin 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 the foreach keyword.
A trivial example iterates over an array of integers:
codeprints


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:
codeprints


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.
codeprints


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:
codeprints


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 hypothetical frob 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
  1. or using the aliases
$list | foreach
$list | %

Extensible Stylesheet Language (XSL)