Kalpana Kalpana (Editor)

Foreach loop

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit
Foreach loop

For each (or foreach) is a control flow statement 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 errors and makes code simpler to read. In object-oriented languages an iterator, even if implicit, is often used as the means of traversal.

Contents

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 does not have any particular order, especially array programming languages, in order to support loop optimization in general and in particular to allow vector processing to process some or all of the items in the collection simultaneously.

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++11, C#, ColdFusion Markup Language (CFML), Cobra, D, Daplex (query language), ECMAScript, Erlang, Java (since 1.5, using the reserved word for for the for loop and the foreach loop), JavaScript, Objective-C (since 2.0), ParaSail, Perl, PHP, 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

ActionScript supports foreach loops by key/index and by value:

Typical usage is as shown, but someArray could be any object, and someObject could be an array.

Ada

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

C

The language C 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 (e.g., array and linked list) or that is extensible to user types.
  • 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)

    Note: idxtype can be removed and typeof(col[0]) used in its place with GCC

    C#

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

    C++11 provides a foreach loop. The syntax is similar to that of Java:

    Currently, 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 )

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

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

    C++/CLI

    The C++/CLI language proposes a construct similar to C#.

    Assuming that myArray is an array of integers:

    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

    Common Lisp provides foreach ability either with the dolist macro:

    or with the mapcar function:

    Object Pascal, 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 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

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

    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

    Haskell

    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.

    Java

    In Java, a foreach-construct was introduced in Java Development Kit (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 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 is sometimes useful to add a hasOwnProperty() test, if supported by the JavaScript engine (for WebKit/Safari, this means "in version 3 or later").

    In ECMAScript 5 it is possible to use the keys method of the Object function to iterate over the own keys of an object more naturally.

    In ECMAScript 5 it's also possible to use the forEach method of a native array.

    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. The EcmaScript 6 standard has for..of for index-less iteration over generators, arrays and more.

    Mint

    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.

    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:

    OCaml

    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:

    or in short way:

    For arrays:

    or in short way:

    ParaSail

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

    Pascal

    In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus:

    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:

    Perl 6

    In Perl 6, a distinct language from Perl 5, for must be used to traverse elements of a list. (foreach is no longer 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:

    Array examples:

    Hash example:

    or

    or

    Direct modification of collection members:

    PHP

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

    Direct modification of collection members:

  • More information
  • 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 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":

    Racket

    or using the conventional Scheme for-each function:

    do-something-with is a one-argument function.

    Ruby

    or

    This can also be used with a hash.

    Scheme

    do-something-with is a one-argument function.

    Swift

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

    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.

    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

    or without type inference

    Windows PowerShell

    From a pipeline

    References

    Foreach loop Wikipedia