For each (or foreach) is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard forstatement. Unlike other for loop constructs, however, foreach loops [cite web |url=http://www.digitalmars.com/d/statement.html#ForeachStatement |title=D Programming Language foreach Statement Documentation |accessdate=2008-08-04 |last= |first= |coauthors= |date= |work= |publisher=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.
The Python programming language is notable in having only a "foreach" loop (called simply for), requiring explicit counting (often via the range function) to achieve "standard" "for" behavior.
yntax
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, Javascript, 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++.
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 keyscite web |url=http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in |title=JavaScript - for each...in statement |accessdate=2008-10-03] .
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 ordercite web |url=http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in#Description |title=JavaScript - for...in statement on arrays |accessdate=2008-10-03] . A regular C-style for loop should be used instead.
PHP
PHP has an idiosyncratic syntax:
foreach($set as $item){ // do something to $item;}
You can also extract the key from the set using this syntax:
Contrary to other languages, in Smalltalk the foreach loop is not a language construct but defined in the class Collection as a method with one parameter, which is the body as a closure. Also, Smalltalk defines collect, select, reject, etc. as known from OCL, however Smalltalk predates OCL by about twenty years.
For Each item As type In set ' do something to itemNext item
Windows PowerShell
foreach ($item in $set) { # do something to $item }
C++
C++ does not have foreach, but its standard library includes a for_each function (in ) 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. [cite web |url=http://doc.trolltech.com/4.2/containers.html#the-foreach-keyword |title=Qt - The Foreach Keyword |accessdate=2008-08-04 |last= |first= |coauthors= |date= |work= |publisher=] There is also a similar macro in boost which performs within a few percent of the equivalent hand-coded loop. [cite web |url=http://boost-sandbox.sourceforge.net/libs/foreach/doc/html/ |title=Boost Library - Foreach Keyword Documentation |accessdate=2008-08-04 |last= |first= |coauthors= |date= |work= |publisher=]
ee also
* Do while loop * For loop * While loop * Map (higher-order function)
Foreach — Viele Programmiersprachen definieren eine For Schleife als eine Kontrollstruktur, mit der man eine Gruppe von Anweisungen (Block) mit einer bestimmten Anzahl von Wiederholungen ausführen kann. Die Definition, wie eine For Schleife auszusehen hat… … Deutsch Wikipedia
Foreach-Schleife — Viele Programmiersprachen definieren eine For Schleife als eine Kontrollstruktur, mit der man eine Gruppe von Anweisungen (Block) mit einer bestimmten Anzahl von Wiederholungen ausführen kann. Die Definition, wie eine For Schleife auszusehen hat… … Deutsch Wikipedia
Цикл foreach — Цикл разновидность управляющей конструкции в высокоуровневых языках программирования, предназначенная для организации многократного исполнения набора инструкций. Также циклом может называться любая многократно исполняемая последовательность… … Википедия
Joinalgorithmen — sind mögliche Strategien (Algorithmen) zur Implementierung von Joins. Die optimale Strategie hängt von Größe und Struktur der am Join beteiligten Relationen, verwendeten oder verwendbaren Indizes, der Größe des Hauptspeichers als auch der Join… … Deutsch Wikipedia
C Sharp syntax — The correct title of this article is C# syntax. The substitution or omission of the # sign is because of technical restrictions. Main article: C Sharp (programming language) This article describes the syntax of the C# programming language. The… … Wikipedia
Comparison of programming languages (mapping) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations … Wikipedia
Iterator — Der Begriff Iterator stammt aus dem Bereich der Softwareentwicklung und bezeichnet einen Zeiger, mit dem über die Elemente einer Liste bzw. durch die Elemente einer Menge iteriert werden kann. Der Iterator wird insbesondere im Bereich der… … Deutsch Wikipedia
D (programming language) — For other programming languages named D, see D (disambiguation)#Computing. D programming language Paradigm(s) multi paradigm: imperative, object oriented, functional, meta Appeared in 1999 (1999) Designed by … Wikipedia
Sprachelemente von C-Sharp — Dieser Artikel bietet eine Übersicht einiger Sprachelemente von C#. Inhaltsverzeichnis 1 Bedingte Ausführung (if, else, switch) 2 Schleifen (for, do, while, foreach) 3 Die Sprunganweisungen break, c … Deutsch Wikipedia