For each (or foreach) is a control flow statement 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 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.
Syntax varies among languages. Most use the simple word for
, roughly as follows:
Programming languages which support foreach loops include ABC, ActionScript, Ada, C++11, C#, ColdFusion Markup Language (CFML), Cobra, D, Daplex (query language), ECMAScript, Erlang, Java (since 1.5, using the reserved word for
for the for loop and the foreach loop), JavaScript, Objective-C (since 2.0), ParaSail, Perl, PHP, Python, REALbasic, Ruby, Scala, Smalltalk, Swift, Tcl, tcsh, Unix shells, Visual Basic .NET, and Windows PowerShell. Notable languages without foreach are C, and C++ pre-C++11.