Foreach loop explained

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

Syntax varies among languages. Most use the simple word for, roughly as follows:

for each item in collection: do something to item

Language support

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 3.0

ActionScript supports the ECMAScript 4.0 Standard[5] for for each .. in[6] which pulls the value at each index.

var foo:Object = ;

for each (var value:int in foo)

// returns "1" then "2"

It also supports for .. in[7] which pulls the key at each index.

for (var key:String in foo)

// returns "apple" then "orange"

Ada

Ada supports foreach loops as part of the normal for loop. Say X is an array:

for I in X'Range loop X (I) := 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 (array, lists, maps...):

for Obj of X loop -- Work on Objend 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(ptrvar, strvar) \

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)

  1. include

/* foreach macro viewing an array of int values as a collection of int values */

  1. define foreach(intpvar, intarr) \

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

  1. include
  2. include

/* foreach macro viewing an array of given type as a collection of values of given type */

  1. define arraylen(arr) (sizeof(arr)/sizeof(arr[0]))
  2. define foreach(idxtype, idxpvar, col, colsiz) \

idxtype* idxpvar; \for (idxpvar = col; idxpvar < (col + colsiz); ++idxpvar)

int main(int argc, char** argv)

C#

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++

C++11 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 (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:

for (auto __anon = begin(myint); __anon != end(myint); ++__anon)

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.

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

int main

Qt, a C++ framework, offers a macro providing foreach loops[11] 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:[12]

  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 (int x in myArray)

ColdFusion Markup Language (CFML)

See main article: ColdFusion Markup Language.

Script syntax

// arraysarrayeach([1,2,3,4,5], function(v));

// 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));

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[k]#

Common Lisp

Common Lisp provides foreach ability either with the dolist macro:(dolist (i '(1 3 5 6 8 10 14 17)) (print i))or the powerful loop macro to iterate on more data types(loop for i in '(1 3 5 6 8 10 14 17) do (print i))

and even with the mapcar function:(mapcar #'print '(1 3 5 6 8 10 14 17))

D

See main article: D (programming language). foreach(item; set)

or

foreach(argument)

Dart

See main article: Dart (programming language). for (final element in someCollection)

Object Pascal, Delphi

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.

for enumerator in collection dobegin //do something hereend;

Eiffel

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

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 gets the index/key (first element) and the value (second element):for index, value := range someCollection

Using the one-value form gets the index/key (first element):for index := range someCollection [13]

Groovy

Groovy supports for loops over collections like arrays, lists and ranges:

def x = [1,2,3,4]for (v in x) // loop over the 4-element array x

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:

for (i = 0; i < x.size; i++)

Collections in Groovy can also be iterated over using the each keywordand a closure. By default, the loop dummy is named it

x.each // print every element of the x arrayx.each // equivalent to line above, only loop dummy explicitly named "i"

Haskell

Haskell allows looping over lists with monadic actions using mapM_ and forM_ (mapM_ with its arguments flipped) from Control.Monad:

code prints
mapM_ print [1..4]1 2 3 4
forM_ "test" $ \char -> do putChar char putChar chartteesstt

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.

Haxe

See main article: Haxe. for (value in iterable)

Lambda.iter(iterable, function(value) trace(value));

Java

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]

for (Type item : iterableCollection)

Java also provides the stream api since java 8:[18] List intList = List.of(1, 2, 3, 4); intList.stream.forEach(i -> System.out.println(i));

JavaScript

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:for (var item of array)

Alternatively, function-based style: [19]

array.forEach(item =>)

For unordered iteration over the keys in an Object, JavaScript features the for...in loop:

for (var key in object)

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").

for (var key in object)

ECMAScript 5 provided Object.keys method, to transfer the own keys of an object into array.[20] var book = ; for(var key of Object.keys(book))

Lua

See main article: Lua (programming language). Source:[21]

Iterate only through numerical index values:for index, value in ipairs(array) do -- do somethingendIterate through all index values:for index, value in pairs(array) do -- do somethingend

Mathematica

In Mathematica, Do will simply evaluate an expression for each element of a list, without returning any value.

In[]:= Do[doSomethingWithItem, {item, list}]

It is more common to use Table, which returns the result of each evaluation in a new list.

In[]:= list = ;

In[]:= Table[item^2, {item, list}]Out[]=

MATLAB

See main article: MATLAB. for item = array%do somethingend

Mint

For each loops are supported in Mint, possessing the following syntax:for each element of list /* 'Do something.' */end

The for (;;) or while (true) infinite loopin Mint can be written using a for each loop and an infinitely long list.[22]

import type/* 'This function is mapped to' * 'each index number i of the' * 'infinitely long list.' */sub identity(x) return xend/* 'The following creates the list' * '[0, 1, 2, 3, 4, 5, ..., infinity]' */infiniteList = list(identity)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 (iterates over keys), NSSet, etc.

NSArray *a = [NSArray new]; // Any container class can be substituted

for(id obj in a)

NSArrays can also broadcast a message to their members:

NSArray *a = [NSArray new];

[a makeObjectsPerformSelector:@selector(printDescription)]

Where blocks are available, an NSArray can automatically perform a block on every contained item:

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"obj %@", obj); if ([obj shouldStopIterationNow]) *stop = YES; }];

The type of collection being iterated will dictate the item returned with each iteration.For example:

NSDictionary *d = [NSDictionary new];

for(id key in d)

OCaml

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:

List.iter (fun x -> print_int x) [1;2;3;4];;

or in short way:

List.iter print_int [1;2;3;4];;

For arrays:

Array.iter (fun x -> print_int x) [|1;2;3;4|];;

or in short way:

Array.iter print_int [|1;2;3;4|];;

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 (the default) // ... do something with Elemend 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 := ["abc", "def", "ghi"];

for each [Str => Tr] of My_Map forward loop // ... do something with Str or Trend 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 (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:

foreach (1, 2, 3, 4)

Array examples:

foreach (@arr)

foreach $x (@arr)

Hash example:

foreach $x (keys %hash)

Direct modification of collection members:

@arr = ('remove-foo', 'remove-bar');foreach $x (@arr)

  1. Now @arr = ('foo', 'bar');

PHP

See main article: PHP syntax and semantics. foreach ($set as $value)

It is also possible to extract both keys and values using the alternate syntax:

foreach ($set as $key => $value)

Direct modification of collection members:

$arr = array(1, 2, 3);foreach ($arr as &$value) // Now $arr = array(2, 3, 4);

// also works with the full syntaxforeach ($arr as $key => &$value)

Python

See main article: Python (programming language). 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 (key, value) 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(len(seq)): # Do something to seq[i]

... though using the enumerate function is considered more "Pythonic":

for i, item in enumerate(seq): # Do stuff with item # Possibly assign it back to seq[i]

R

See main article: R (programming language). for (item in object)

As for ... in is the only kind of for loop in R, the equivalent to the "counter" loop found in other languages is...

for (i in seq_along(object))

Racket

See main article: Racket (programming language). (for ([item set]) (do-something-with item))

or using the conventional Scheme for-each function:

(for-each do-something-with a-list)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 (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:

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

See main article: Ruby (programming language). set.each do |item| # do something to itemend

or

for item in set # do something to itemend

This can also be used with a hash.

set.each do |key,value| # do something to key # do something to valueend

Rust

See main article: Rust (programming language). The for loop has the structure for in . 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 [[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.

let mut numbers = vec![1, 2, 3];

// 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);

Scala

See main article: Scala (programming language). // return list of modified elementsitems map items map multiplyByTwo

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")

Scheme

See main article: Scheme (programming language). (for-each do-something-with a-list)do-something-with is a one-argument function.

Smalltalk

See main article: Smalltalk. collection do: [:item| "do something to item" ]

Swift

Swift uses the forin construct to iterate over members of a collection.[23]

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

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

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:

Visual Basic (.NET)

See main article: 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

See main article: COMMAND.COM and cmd.exe. Invoke a hypothetical frob command three times, giving it a color name each time.C:\>FOR %%a IN (red green blue) DO frob %%a

Windows PowerShell

See main article: Windows PowerShell. foreach ($item in $set)

From a pipeline

$list | ForEach-Object

  1. or using the aliases

$list | foreach $list | %

XSLT

See main article: XSLT. [24]

See also

Notes and References

  1. Web site: D Programming Language foreach Statement Documentation. 2008-08-04. Digital Mars.
  2. Web site: SWI-Prolog – foreach/2 . Swi-prolog.org . 2020-02-10.
  3. Web site: Rebol.
  4. Web site: Red Programming Language.
  5. Web site: Proposed ECMAScript 4th Edition – Language Overview . 2020-02-21.
  6. Web site: for each..in . 2020-02-21.
  7. Web site: for..in . 2020-02-21.
  8. Web site: C++11 Features in Visual C++ 11 - Visual C++ Team Blog - Site Home - MSDN Blogs . Blogs.msdn.com . 2011-09-12 . 2013-08-04.
  9. Web site: Range-based for loop (since C++11) . en.cppreference.com . 2018-12-03.
  10. Web site: std::for_each - cppreference . en.cppreference.com . 2017-09-30.
  11. Web site: Qt 4.2: Generic Containers . Doc.qt.digia.com . 2013-08-04 . https://web.archive.org/web/20151123090839/http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword . 2015-11-23 . dead .
  12. Web site: Eric Niebler . Chapter 9. Boost.Foreach - 1.53.0 . Boost.org . 2013-01-31 . 2013-08-04.
  13. Web site: Range Clause . The Go Programming Language . The Go Programming Language Specification . October 20, 2013.
  14. "Enhanced for Loop - This new language construct[...]"Web site: Java Programming Language, Section: Enhancements in JDK 5. 2009-05-26. 2004. Sun Microsystems, Inc..
  15. "The For-Each Loop"Web site: The For-Each Loop. 2009-05-10. 2008. Sun Microsystems, Inc..
  16. "Implementing this interface allows an object to be the target of the "foreach" statement."Web site: Iterable (Java Platform SE 6). 2009-05-12. 2004. Sun Microsystems, Inc..
  17. Book: Bloch, Joshua. "Effective Java: Programming Language Guide" . Addison-Wesley . third . 978-0134685991. 2018.
  18. Book: Bloch, Joshua. "Effective Java: Programming Language Guide" . Addison-Wesley . third . 978-0134685991. 2018.
  19. Web site: Array.prototype.forEach - JavaScript | MDN. 16 December 2023 .
  20. Web site: Object.keys . Mozilla Developer Network . May 7, 2014.
  21. Web site: Lua Programming/Tables - Wikibooks, open books for an open world. en.wikibooks.org. en. 2017-12-06.
  22. Web site: Mint Tutorial . 20 October 2013 . Chu, Oliver.
  23. Web site: Control Flow — the Swift Programming Language (Swift 5.5).
  24. Web site: XSLT Element . W3Schools.com.