Share on Facebook Share on Twitter Email
Answers.com

Foreach

 
Wikipedia: Foreach

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

Syntax

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

for item in collection:
  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

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.

C#

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

Microsoft Visual C++ does support a nonstandard for each construct in managed and native code.[4]

D

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

Delphi

Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section.

for enumerator in collection do
begin
  //do something here
end;

Java

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

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

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[9]. 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 object Prototype_(computer_science): therefore it is called via the following method:

var my_array = [ 1, 2, 3 ];
 
/*
   The first argument to the forEach method must be a function.
   When called, this function receives the current item in the loop
   as its first argument.
*/
 
function alert_each_item( current_item )
{
    alert( current_item );
}
 
my_array.forEach( alert_each_item );
 
// same as the above, with an anonymous function defined in the method call:
 
my_array.forEach (
   function( current_item )
   {
       alert( current_item );
   }
);
 
// With chaining, the forEach method call can also be applied directly to an array:
 
[ 4, 5, 6 ] . forEach( alert_each_item );
"list of words" . split(" ") . forEach( alert_each_item );

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

Ocaml

Ocaml does not have foreach statement but the standard library contains function to iter on lists and arrays.

List.iter (fun x -> print_int x) [1;2;3;4];;
Array.iter (fun x -> print_int x) [|1;2;3;4|];;

Perl

In Perl, foreach 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:

foreach (1, 2, 3, 4){
print $_;
}


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
}

Direct modification of collection members:

@arr = ( 'remove-foo', 'remove-bar' );
foreach $x (@arr){
    $x =~ s/remove-//;
}
# Now @arr = ('foo', 'bar');

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

Python

for item in iterable_collection:
  # do something with 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.items(): # direct iteration on a dict iterates on its keys
    # do stuff

As for...in is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is...

for i in range( 0, len(seq), 1 ):    # range( start, stop, step )
    # do something to seq[i]

... though using the enumerate function is considered more "Pythonic":

for i, item in enumerate(seq):
    # do stuff with item
    # possibly assign it back to seq[i]

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

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
}

See also

References


Search unanswered questions...
Enter a question here...
Search: All sources Community Q&A Reference topics
 
 

 

Copyrights:

Wikipedia. This article is licensed under the Creative Commons Attribution/Share-Alike License. It uses material from the Wikipedia article "Foreach" Read more