Foreach
Encyclopedia
For each is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for
For loop
In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement....

 statement
Statement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...

. Unlike other for loop constructs, however, foreach loops 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 error
Off-by-one error
An off-by-one error is a logical error involving the discrete equivalent of a boundary condition. It often occurs in computer programming when an iterative loop iterates one time too many or too few...

s and makes code simpler to read. In object-oriented languages an iterator
Iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container. Various types of iterators are often provided via a container's interface...

, even if implicit, is often used as the means of traversal.

Syntax

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

for each item in collection:
do something to item

Language support

Some of the languages with support for foreach loops include ABC, ActionScript
ActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

, Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

, C++11, C#, Cobra
Cobra (programming language from Cobra Language LLC)
Cobra is an object-oriented programming language produced by Cobra Language LLC. Cobra is designed by Chuck Esterbrook, and runs on the Microsoft .NET and Mono platforms. It is strongly influenced by Python, C#, Eiffel, Objective-C, and other programming languages. It supports both static and...

, D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

, ECMAScript
ECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...

, Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 (since 1.5), JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

, Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

 (since 2.0), Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

, PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, REALbasic
REALbasic
Realbasic is the object-oriented dialect of the BASIC programming language used in Real Studio, a programming environment, developed and commercially marketed by Real Software, Inc of Austin, Texas for Mac OS X, Microsoft Windows, 32-bit x86 Linux and the web.- Language features :RB is a strongly...

, Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

, Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

, Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

, tcsh
Tcsh
tcsh is a Unix shell based on and compatible with the C shell . It is essentially the C shell with programmable command line completion, command-line editing, and a few other features.-History:...

, Daplex
Daplex
Daplex is an old computer language used for creating distributed database systems and can be used as a global query language.-Example of Daplex Local Schemata:Type EMPLOYEE is entityName: stringSSN: integerADDRESS: stringSALARY: Floatend entity;...

 (a query language), Unix shell
Unix shell
A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems...

s, Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...

 and Windows PowerShell
Windows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...

. Notable languages without foreach are C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 and C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 (prior to C++11).

ActionScript
ActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

 

ActionScript supports foreach loops by key/index and by value:


for ( var key:String in someObject ) {
var value = someObject[key];
trace( "someObject[" + key + "] = " + someObject[key] );
}

for each ( var value in someArray ) {
trace( typeof value + " " + value );
}


Note: someArray could be any object and someObject could be an array, but typical usage is as shown.

Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

 

Ada supports foreach loops as part of the normal for loop
For loop
In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement....

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

Assuming that myArray is an array of integers:

foreach (int x in myArray)
{
Console.WriteLine(x);
}

C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

C++11 provides a for each loop. The syntax is taken from Java and looks like this:

  1. include

int main
{
int myint[] = {1,2,3,4,5};

for (int& i: myint)
{
std::cout << i << std::endl;
}
}


Currently, C++11 range-based for statements have been implemented in GCC
GNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...

 (since version 4.6) and clang
Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages. It uses the Low Level Virtual Machine as its back end, and Clang has been part of LLVM releases since LLVM 2.6....

 (since version 3.0).

Qt, a C++ framework, offers a macro providing foreach loops using the STL iterator interface:

  1. include
  2. include


int main {
QList list;
list << 1 << 2 << 3 << 4 << 5;
foreach (int i, list) {
qDebug << i;
}
}

Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

 

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 = [NSArray new]; // Any container class can be substituted

for(id obj in a) { // 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", bj description] UTF8String]); // Must use UTF8String with %s
NSLog(@"%@", obj); // Leave as an object
}


NSArrays can also broadcast a message to their members:

NSArray *a = [NSArray new];

[a makeObjectsPerformSelector:@selector(printDescription)];


Where blocks
Blocks (C language extension)
Blocks are a nonstandard extension added by Apple Inc. to the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages...

 are available, an NSArray can automatically perform a block on every contained item:


[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSLog(@"obj %@", obj);
if ([obj shouldStopIterationNow])
*stop = YES;
}];


The type of collection being iterated will dictate the item returned with each iteration.
For example:


NSDictionary *d = [NSDictionary new];

for(id key in d) {
NSObject *obj = [d objectForKey:key]; // We use the (unique) key to access the (possibly non-unique) object.
NSLog(@"%@", obj);
}

D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

 


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

Delphi
Object Pascal
Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...

 

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;

Eiffel
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...

 

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:

across my_list as ic loop print (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.

The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword loop is replaced by either all (effecting universal quantification
Universal quantification
In predicate logic, universal quantification formalizes the notion that something is true for everything, or every relevant thing....

) or some (effecting existential quantification
Existential quantification
In predicate logic, an existential quantification is the predication of a property or relation to at least one member of the domain. It is denoted by the logical operator symbol ∃ , which is called the existential quantifier...

).

This iteration is a boolean expression which is true if all items in my_list have counts greater than three:


across my_list as ic all ic.item.count > 3 end


The following is true if at least one item has a count greater than three:


across my_list as ic some ic.item.count > 3 end

Go
Go (programming language)
Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being...

 

Go's foreach loop can be used to loop over an array, slice, string, map, or channel.

Using the two-value form, we get the index/key (first element) and the value (second element):

for index, value := range someCollection {
// do something to index and value
}


Using the one-value form, we get the index/key (first element):

for index := range someCollection {
// do something to index
}

http://golang.org/doc/go_spec.html#RangeClause

Groovy 

Groovy supports for loops over collections like arrays, lists and ranges:

def x = [1,2,3,4]
for (v in x) // loop over the 4-element array x
{
println v
}

for (v in [1,2,3,4]) // loop over 4-element literal list
{
println v
}

for (v in 1..4) // loop over the range 1..4
{
println v
}


Groovy also supports a C-style for loop with an array index:

for (i = 0; i < x.size; i++)
{
println x[i]
}


Collections in Groovy can also be iterated over using the each keyword
and a closure. By default, the loop dummy is named it

x.each{ println it } // print every element of the x array
x.each{i-> println i} // equivalent to line above, only loop dummy explicitly named "i"

Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

 


mapM_ someFunction someList

haXe
HaXe
haXe is a versatile open-source high-level multiplatform programming language described on its website as a "universal language".It can produce:* Flash applications and games* Multi-platform client-side web applications* Apache CGI web applications...

 


for (value in iterable) {
trace(value);
}

Lambda.iter(iterable, function(value) trace(value));

Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 

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

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

JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 

For iterating over Array objects, JavaScript 1.6 (ECMA-262 Edition 5) offers a forEach method.

Importantly, Microsoft Internet Explorer prior to version 9 does not natively support this method (or any of several other Array object iteration methods introduced after JavaScript 1.5); for information on implementing these methods for backwards compatibility, see the Mozilla Developer Center: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach.


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 );



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


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


In order to limit the iteration to the object's own properties, excluding the ones 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 (var strProperty in objObject) {
if(objObject.hasOwnProperty(strProperty )) {
/*
do something to:
objObject [strProperty]
*/
}
}


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

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

Ocaml 

Since Ocaml is a functional language, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.

For Lists :

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

or in short way :

List.iter print_int [1;2;3;4];;


For Arrays :

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

or in short way :

Array.iter print_int [|1;2;3;4|];;

Pascal
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...

 

The ISO 10206:1990 standard introduced iteration over set types in Pascal:


var
elt: ElementType;
eltset: set of ElementType;

{...}

for elt in eltset do
{ ... do something with elt }

Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 

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 @arr
print $x;
}


Hash example:


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


Direct modification of collection members:


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



PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 

PHP has an idiosyncratic syntax:


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


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


Direct modification of collection members:

$arr = array(1, 2, 3);
foreach ($set as &$value) { // note the &, $value is a reference to the original value inside $set
$value++;
}
// Now $arr = array(2, 3, 4);

// also works with the full syntax
foreach ($set as $key => &$value) {
$value++;
}


Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 


for item in iterable_collection:
# do something with item


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


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(len(seq)):
# 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]

Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

 


set.each do |item|
# do something to item
end

or

for item in set
# do something to item
end

You can also use this with a hash.



set.each do |item,value|
# do something to item
# do something to value
end

Racket 


(for ([item set])
(do-something-with item))

or using the conventional Scheme for-each function:

(for-each do-something-with a-list)

Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

 


collection do: [|item| # do something to item ]


Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

 

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
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...

 


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

XSL
XSL
The three-letter abbreviation XSL may have multiple meanings, as described below:* In computing, the Extensible Stylesheet Language: a set of language technologies for defining XML document transformation and presentation* XSL Formatting Objects...


<!-- do something for the elements in <set> -->
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK