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 [1] 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. In object-oriented languages an iterator, even if implicit, is often used as the means of traversal.

The Python programming language is notable in having only a foreach loop (called simply for), requiring explicit counting (often via the range function) to achieve "standard" for behavior.

Contents

Syntax

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

for item in set:
  do something to item

Language support

Some of the languages with support for foreach loops include ABC, Ada, C#, Cobra, D, ECMAScript, Java, Javascript, Perl, PHP, Python, REALbasic, Ruby, Smalltalk, Tcl, tcsh, Daplex (a query language), Unix shells, Visual Basic .NET and Windows PowerShell. Notable languages without foreach are C and C++.

Ada

Wikibooks
Wikibooks' Ada_Programming has more about this subject:

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;
Note
This syntax is mostly used on arrays but will also work with other types when a full iteration is needed.

Cobra

for item in collection
    print item
    item.doSomething
 
for item in collection, item.doSomething
 
for item in collection, if item.isFoo, item.doSomething

Curly bracket programming language

In curly bracket programming languages, the syntax is similar to this:

C#

foreach (type item in set) {
  // do something to item
}

D

foreach(item; set) {
  // do something to item
}
or
foreach(argument) {
  // pass value
}

Java

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

JavaScript

for (var strProperty in objObject) {
  /*
    do something to:
    objObject [strProperty]
  */
}

JavaScript also has a for each...in statement, which iterates over the values in the object, not the keys[2].

In order to limit the iteration to the object's own properties, excluding the ones inherited through the prototype chain, it is advisable to add a hasOwnProperty() test, if supported by the JavaScript engine (for WebKit/Safari, this means "in version 3 or later").

for (var strProperty in objObject) {
  if(objObject.hasOwnProperty(strProperty )) {
    /*
      do something to:
      objObject [strProperty]
    */
  }
}

Also note that it is inadvisable to use either a for...in or for each...in statement on an array in JavaScript, due to the above issue, and also because it is not guaranteed to iterate over the elements in any particular order[3]. A regular C-style for loop should be used instead.

PHP

PHP has an idiosyncratic syntax:

foreach($set as $item)
{
  // do something to $item;
}

You can also extract the key from the set using this syntax:

$set = array (
   "name" => "John",
   "address" => "123 Main Street"
);
 
foreach ($set as $key => $value) {
  echo "{$key} has a value of {$value}";
}

The result would be:

name has a value of John
address has a value of 123 Main Street

Python

for item in set:
  # do something to item

Smalltalk

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

Visual Basic .NET

For Each item As type In set
 ' do something to item
Next item

Windows PowerShell

foreach ($item in $set) {
  # do something to $item
}

C++

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.[4] There is also a similar macro in boost which performs within a few percent of the equivalent hand-coded loop. [5]

See also

References

  1. ^ "D Programming Language foreach Statement Documentation". usually. Retrieved on 2008-08-04.
  2. ^ "JavaScript - for each...in statement". Retrieved on 2008-10-03.
  3. ^ "JavaScript - for...in statement on arrays". Retrieved on 2008-10-03.
  4. ^ "Qt - The Foreach Keyword". Retrieved on 2008-08-04.
  5. ^ "Boost Library - Foreach Keyword Documentation". Retrieved on 2008-08-04.

No comments have been added.



Your name:

City:

Country:

Your comments:

Security check *
(Please enter the number into adjoining box)