For each (or foreach) is a control flow statement for traversing items in a collection. Foreach is usually used in place of a standard forstatement. 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 avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages an iterator, even if implicit, is often used as the means of traversal.

The foreach statement in some languages has some defined order, processing each item in the collection from the first to the last. The foreach statement in many other languages does not have any particular order, especially array programming languages, in order to support loop optimization in general and in particular to allow vector processing to process some or all of the items in the collection simultaneously.

The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword across.

In this example, every element of the structure my_list is printed:

acrossmy_listasicloopprint(ic.item)end

The local entity ic is an instance of the library class ITERATION_CURSOR. The cursor's feature item provides access to each structure element. Descendants of class ITERATION_CURSOR can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (my_list in the example) are based on classes that inherit from the library class ITERABLE.

It's also possible to generalize those functions to work on applicative functors rather than monads and any data structure that is traversable using traverse (for with its arguments flipped) and mapM (forM with its arguments flipped) from Data.Traversable.

For unordered iteration over the keys in an Object, JavaScript features the for...in loop:

for(varkeyinobject){// Do stuff with object[key]}

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

for(varkeyinobject){if(object.hasOwnProperty(key)){// Do stuff with object[key]}}

In ECMAScript 5 it is possible to use the keys method of the Object function to iterate over the own keys of an object more naturally. [9]

Gecko’s JavaScript engine also has a for each...in statement, which iterates over the values in the object, not the keys.[11]

Also note that it is inadvisable to use either a for...in or for each...in statement on an Array object in JavaScript, due to the above issue of properties inherited from prototypes, and also because it only iterates over existent keys and is not guaranteed to iterate over the elements in any particular order.[12] A regular C-style for loop should be used instead. The EcmaScript 6 standard has for..of for index-less iteration over generators, arrays and more.

Foreach loops, called Fast enumeration, are supported starting in Objective-C 2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc.

NSArray*a=[NSArraynew];// Any container class can be substitutedfor(idobjina){// Note the dynamic typing (we do not need to know the// Type of object stored in 'a'. In fact, there can be// many different types of object in the array.printf("%s\n",[[objdescription]UTF8String]);// Must use UTF8String with %sNSLog(@"%@",obj);// Leave as an object}

The ParaSail parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:

varCon:Container<Element_Type>:=...// ...foreachElemofConconcurrentloop// loop may also be "forward" or "reverse" or unordered (the default)// ... do something with Elemendloop

ParaSail also supports filters on iterators, and the ability to refer to both the key and the value of a map. Here is a forward iteration over the elements of "My_Map" selecting only elements where the keys are in "My_Set":

varMy_Map:Map<Key_Type=>Univ_String,Value_Type=>Tree<Integer>>:=...constMy_Set:Set<Univ_String>:=["abc","def","ghi"];foreach[Str=>Tr]ofMy_Map{StrinMy_Set}forwardloop// ... do something with Str or Trendloop

In Perl, foreach (which is equivalent to the shorter for) 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 @arrprint$x;}

Hash example:

foreach$x(keys%hash){print$x." = ".$hash{$x};# $x is a key in %hash and $hash{$x} is its value}

In Perl 6, a distinct language from Perl 5, for must be used to traverse elements of a list. (foreach is no longer allowed.) The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s).

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

foreach($setas$key=>$value){echo"{$key} has a value of {$value}";}

Direct modification of collection members:

$arr=array(1,2,3);foreach($arras&$value){// Note the &, $value is a reference to the original value inside $arr$value++;}// Now $arr = array(2, 3, 4);// also works with the full syntaxforeach($arras$key=>&$value){$value++;}

Swift uses the for…in construct to iterate over members of a collection.[14]

forthinginsomeCollection{// do something with thing}

The for…in loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times.

foriin0..<10{// 0..<10 constructs a half-open range, so the loop body// is repeated for i = 0, i = 1, …, i = 9.}foriin0...10{// 0...10 constructs a closed range, so the loop body// is repeated for i = 0, i = 1, …, i = 9, i = 10.}