Foreach

From Wikipedia, the free encyclopedia

Jump to: navigation, search

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.

Contents

[edit] Syntax

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

for item in collection:
  do something to item

[edit] 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++.

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

[edit] C#

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

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

[edit] D

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

[edit] Java

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

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

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

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

[edit] Perl

In Perl, foreach can be used to traverse elements of an array or a hash-map.

Array examples:

foreach (@arr){
print $_;
}
foreach $x(@arr) { #$x is the element in @arr
print $x;
}

Hash example:

foreach $x (keys %hash) {
    $y = $hash{$x}; # $x is the key in %hash and y is the element it is pointing to
}

[edit] PHP

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}";
}

[edit] Python

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

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

[edit] Visual Basic .NET

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

[edit] Windows PowerShell

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

[edit] See also

[edit] References

Personal tools