Jump to content

Foreach loop

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Daemonax (talk | contribs) at 13:29, 6 June 2009 (→‎JavaScript). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

Several languages, including Tcl and Python, have only a foreach loop, requiring explicit counting to achieve "standard" for behavior.

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 (since 1.5), Javascript, Objective-C (since 2.0), 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 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.
foreach (type item in set) {
  // do something to item
}
foreach(item; set) {
  // do something to item
}
or
foreach(argument) {
  // pass value
}

A foreach-construct was introduced in JDK 5.0.[2] Official sources use several names for the construct. It is referred to as the "Enhanced for Loop"[2] the "For-Each Loop"[3] and the "foreach statement".[4]

for (type item: set) {
  // do something to item
}
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[5].

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[6]. A regular C-style for loop should be used instead.

Some implementations of JavaScript, most notably the gecko layout engine used by browsers, including FireFox offer a method of implementing a foreach loop via a prototype of the array objectPrototype_(computer_science): therefore it is called via the following method:

var my_array = new Array("one","two","three");
// the same as:
var my_array2 = ["one","two","three"];

// use the forEach statement to write code to the document using the [planned to be but isn't] depreciated document.write method.
// the forEach statement requires the first argument to be a (referenced or anonymous) function who's first argument is the variable 
// to pass the current looped member of the array to.

function alert_each_member(current_member){
    alert(current_member);
    return true;
}

my_array.forEach(alert_each_member);

// the following example is the same as the above, but with an anonymous function:

my_array2.forEach(function(current_member){
    alert(current_member);
    return true;
});

// and, though this is almost always unnecessary, one could apply forEach loop directly to an array:

["one","two","three"].forEach("...");

Many JavaScript libraries implement this prototype if it is not natively implemented, by first testing if the function Array.prototype.forEach exists, then implementing it if it does not. The Mozilla Developer Center has information regarding this [1].

PHP has an idiosyncratic syntax:

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

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

foreach ($set as $key => $value) {
  echo "{$key} has a value of {$value}";
}
for item in iterable_collection:
  # do something to item

Python's tuple assignment, fully available in its foreach loop, also makes iterating on (key, value) pairs in associative arrays trivial:

for key, value in some_dict.iteritems(): # direct iteration on a dict iterates on its keys
    # do stuff

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. The code below prints:
1 2
3 4
5 6

foreach {i j} {1 2 3 4 5 6} {
   puts "$i $j"
}

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:

foreach i {1 2 3} j {a b c}  {
   puts "$i $j"
}

This prints:
1 a
2 b
3 c

For Each item As type In set
 ' do something to item
Next item
foreach ($item in $set) {
  # do something to $item
}

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

See also

References

  1. ^ "D Programming Language foreach Statement Documentation". Retrieved 2008-08-04. {{cite web}}: Cite has empty unknown parameter: |coauthors= (help)
  2. ^ a b "Enhanced for Loop - This new language construct[...]" "Java Programming Language, Section: Enhancements in JDK 5". Sun Microsystems, Inc. 2004. Retrieved 2009-05-26.
  3. ^ "The For-Each Loop" "The For-Each Loop". Sun Microsystems, Inc. 2008. Retrieved 2009-05-10.
  4. ^ "Implementing this interface allows an object to be the target of the "foreach" statement." "Iterable (Java Platform SE 6)". Sun Microsystems, Inc. 2004. Retrieved 2009-05-12.
  5. ^ "JavaScript - for each...in statement". Retrieved 2008-10-03.
  6. ^ "JavaScript - for...in statement on arrays". Retrieved 2008-10-03.
  7. ^ "Qt - The Foreach Keyword". Retrieved 2008-08-04. {{cite web}}: Cite has empty unknown parameter: |coauthors= (help)
  8. ^ "Boost Library - Foreach Keyword Documentation". Retrieved 2008-08-04. {{cite web}}: Cite has empty unknown parameter: |coauthors= (help)