language-icon Old Web
English
Sign In

Foreach loop

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. 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, especially array programming languages, does not have any particular order. This simplifies loop optimization in general and in particular allows vector processing of items in the collection concurrently. 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, Lua, 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. Ada supports foreach loops as part of the normal for loop. Say X is an array:

[ "Programming language" ]
Parent Topic
Child Topic
    No Parent Topic