Foreach

From Wikipedia, the free encyclopedia

For each (or foreach) 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 can potentially avoid off-by-one errors and make code simpler to read.

The Python programming language is notable in having no for loop other than foreach - iterator variables are nonexistent in the language.

[edit] Syntax

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

for item in set:
  do something to item

In curly bracket programming languages like Java and C#, the syntax is similar to this:

for (type item : set) {
  do something to item
}

PHP has an idiosyncratic syntax:

foreach($set as $item)
  do something to $item;

[edit] Language support

Some of the languages with support for foreach loops include C#, D, ECMAScript, Java, Javascript, Perl, PHP, Python, REALbasic, Ruby, Smalltalk, Tcl, tcsh,Daplex (a query language), Unix shells, and Visual Basic. One notable language without foreach is C.

Contrary to other languages, in Smalltalk the foreach loop is not a language construct but defined in the class Collection as a method with one parameter, which is the body as a closure. Also, Smalltalk defines collect, select, reject etc as known from OCL, however Smalltalk predates OCL by about twenty years.

coll := Array with: 'foo' with: 'bar' with: 'qux'.
coll do: [ each | Transcript print: each ].

C++ does not have foreach, but its standard library includes a for_each function (in <algorithm>) which applies a function to all items between two iterators, and the Qt toolkit provides a foreach pseudo-keyword for its container classes, implemented as a macro.[1] There is also a similar macro in boost.[2]

In other languages