Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Foreach loop
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Control flow statement for traversing items in a collection}} {{for|"for all" in logic (∀)|Universal quantification}} [[File:For-Loop-Mint-Programming-Language-Type-2.gif|thumb|{{mono|foreach}} loops are almost always used to iterate over items in a sequence of elements.]] {{Loop constructs}}<!-- DO NOT remove. Discuss navigation concept at [[Talk:Do while loop#Helpbox experiment]] --> In [[computer programming]], '''foreach loop''' (or '''for-each loop''') is a [[control flow]] statement for traversing items in a [[Collection class|collection]]. {{mono|foreach}} is usually used in place of a standard {{mono|[[For loop|for]]}} loop [[Statement (computer science)|statement]]. Unlike other {{mono|for}} loop constructs, however, {{mono|foreach}} loops<ref>{{cite web | url=http://www.digitalmars.com/d/statement.html#ForeachStatement | title=D Programming Language <code>foreach</code> Statement Documentation | access-date=2008-08-04 | publisher=Digital Mars }}</ref> usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this {{mono|x}} times". This avoids potential [[off-by-one error]]s and makes code simpler to read. In [[object-oriented]] languages, an [[iterator]], even if implicit, is often used as the means of traversal. The {{mono|foreach}} statement in some languages has some defined order, processing each item in the collection from the first to the last. The {{mono|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 == Syntax varies among languages. Most use the simple word <code>for</code>, although other use the more logical word <code>foreach</code>, roughly as follows: foreach(key, value) in collection { # Do something to value # } == Language support == [[Programming language]]s which support foreach loops include [[ABC (programming language)|ABC]], [[ActionScript]], [[Ada (programming language)|Ada]], [[C++]] (since [[C++11]]), [[C Sharp (programming language)|C#]], [[ColdFusion Markup Language]] (CFML), [[Cobra (programming language)|Cobra]], [[D (programming language)|D]], [[Daplex]] (query language), [[Delphi (software)|Delphi]], [[ECMAScript]], [[Erlang (programming language)|Erlang]], [[Java (programming language)|Java]] (since 1.5), [[JavaScript]], [[Lua (programming language)|Lua]], [[Objective-C]] (since 2.0), [[ParaSail (programming language)|ParaSail]], [[Perl]], [[PHP]], [[Prolog]],<ref>{{Cite web |url=https://www.swi-prolog.org/pldoc/man?predicate=foreach/2 |title=SWI-Prolog – foreach/2 |website=Swi-prolog.org |access-date=2020-02-10}}</ref> [[Python (programming language)|Python]], [[R (programming language)|R]], [[REALbasic]], [[Rebol]],<ref>{{Cite web |url=http://www.rebol.com/ |title=Rebol}}</ref> [[Red (programming language)|Red]],<ref>{{Cite web |url=https://www.red-lang.org/ |title=Red Programming Language}}</ref> [[Ruby (programming language)|Ruby]], [[Scala (programming language)|Scala]], [[Smalltalk]], [[Swift (programming language)|Swift]], [[Tcl]], [[tcsh]], [[Unix shell]]s, [[Visual Basic (.NET)]], and [[Windows PowerShell]]. Notable languages without foreach are [[C (programming language)|C]], and C++ pre-C++11. === ActionScript 3.0 === [[ActionScript]] supports the ECMAScript 4.0 Standard<ref>{{cite web|url=https://www.ecma-international.org/activities/Languages/Language%20overview.pdf |title=Proposed ECMAScript 4th Edition – Language Overview |access-date=2020-02-21}}</ref> for <code>for each .. in</code><ref>{{cite web|url=https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#for_each..in |title=for each..in |access-date=2020-02-21}}</ref> which pulls the value at each index. <syntaxhighlight lang="actionscript3"> var foo:Object = { "apple":1, "orange":2 }; for each (var value:int in foo) { trace(value); } // returns "1" then "2" </syntaxhighlight> It also supports <code>for .. in</code><ref>{{cite web|url=https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#for..in |title=for..in |access-date=2020-02-21}}</ref> which pulls the key at each index. <syntaxhighlight lang="actionscript3"> for (var key:String in foo) { trace(key); } // returns "apple" then "orange" </syntaxhighlight> === Ada === {{Wikibooks|Ada Programming|Control}} [[Ada (programming language)|Ada]] supports foreach loops as part of the normal [[for loop]]. Say X is an [[Array data structure|array]]: <syntaxhighlight lang="Ada"> for I in X'Range loop X (I) := Get_Next_Element; end loop; </syntaxhighlight> This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed. Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...): <syntaxhighlight lang="Ada"> for Obj of X loop -- Work on Obj end loop; </syntaxhighlight> === C === The [[C (programming language)|C]] language does not have collections or a foreach construct. However, it has several standard data structures that can be used as collections, and foreach can be made easily with a [[C macro|macro]]. However, two obvious problems occur: * The macro is unhygienic: it declares a new variable in the existing scope which remains after the loop. * One foreach macro cannot be defined that works with different collection types (e.g., array and linked list) or that is extensible to user types. C string as a collection of char <syntaxhighlight lang="c" highlight="4-6" line> #include <stdio.h> /* foreach macro viewing a string as a collection of char values */ #define foreach(ptrvar, strvar) \ char* ptrvar; \ for (ptrvar = strvar; (*ptrvar) != '\0'; *ptrvar++) int main(int argc, char** argv) { char* s1 = "abcdefg"; char* s2 = "123456789"; foreach (p1, s1) { printf("loop 1: %c\n", *p1); } foreach (p2, s2) { printf("loop 2: %c\n", *p2); } return 0; } </syntaxhighlight> C int array as a collection of int (array size known at compile-time) <syntaxhighlight lang="c" highlight="4-6" line> #include <stdio.h> /* foreach macro viewing an array of int values as a collection of int values */ #define foreach(intpvar, intarr) \ int* intpvar; \ for (intpvar = intarr; intpvar < (intarr + (sizeof(intarr)/sizeof(intarr[0]))); ++intpvar) int main(int argc, char** argv) { int a1[] = {1, 1, 2, 3, 5, 8}; int a2[] = {3, 1, 4, 1, 5, 9}; foreach (p1, a1) { printf("loop 1: %d\n", *p1); } foreach (p2, a2) { printf("loop 2: %d\n", *p2); } return 0; } </syntaxhighlight> Most general: string or array as collection (collection size known at run-time) : ''{{code|idxtype}} can be removed and <code>[[typeof]](col[0])</code> used in its place with [[GNU Compiler Collection|GCC]]'' <syntaxhighlight lang="c" highlight="5-8" line> #include <stdio.h> #include <string.h> /* foreach macro viewing an array of given type as a collection of values of given type */ #define arraylen(arr) (sizeof(arr)/sizeof(arr[0])) #define foreach(idxtype, idxpvar, col, colsiz) \ idxtype* idxpvar; \ for (idxpvar = col; idxpvar < (col + colsiz); ++idxpvar) int main(int argc, char** argv) { char* c1 = "collection"; int c2[] = {3, 1, 4, 1, 5, 9}; double* c3; int c3len = 4; c3 = (double*)calloc(c3len, sizeof(double)); c3[0] = 1.2; c3[1] = 3.4; c3[2] = 5.6; c3[3] = 7.8; foreach (char, p1, c1, strlen(c1)) { printf("loop 1: %c\n", *p1); } foreach (int, p2, c2, arraylen(c2)) { printf("loop 2: %d\n", *p2); } foreach (double, p3, c3, c3len) { printf("loop 3: %.1lf\n", *p3); } return 0; } </syntaxhighlight> === C# === In [[C Sharp (programming language)|C#]], assuming that myArray is an array of integers: <syntaxhighlight lang="csharp"> foreach (int x in myArray) { Console.WriteLine(x); } </syntaxhighlight> [[Language Integrated Query]] (LINQ) provides the following syntax, accepting a [[Delegate (CLI)|delegate]] or [[Lambda (programming)|lambda expression]]: <syntaxhighlight lang="csharp"> myArray.ToList().ForEach(x => Console.WriteLine(x)); </syntaxhighlight> === C++ === [[C++11]] provides a foreach loop. The syntax is similar to that of [[Foreach loop#Java|Java]]: <syntaxhighlight lang="Cpp"> #include <iostream> int main() { int myint[] = {1, 2, 3, 4, 5}; for (int i : myint) { std::cout << i << '\n'; } } </syntaxhighlight> C++11 range-based for statements have been implemented in [[GNU Compiler Collection]] (GCC) (since version 4.6), [[Clang]] (since version 3.0) and [[Visual C++]] 2012 (version 11 <ref>{{cite web|url=http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx |title=C++11 Features in Visual C++ 11 - Visual C++ Team Blog - Site Home - MSDN Blogs |publisher=Blogs.msdn.com |date=2011-09-12 |access-date=2013-08-04}}</ref>) The range-based <code>for</code> is [[syntactic sugar]] equivalent to: <syntaxhighlight lang="Cpp"> for (auto __anon = begin(myint); __anon != end(myint); ++__anon) { auto i = *__anon; std::cout << i << '\n'; } </syntaxhighlight> The compiler uses [[argument-dependent lookup]] to resolve the <code>begin</code> and <code>end</code> functions.<ref>{{cite web|url=https://en.cppreference.com/w/cpp/language/range-for |title=Range-based for loop (since C++11) |publisher=en.cppreference.com |access-date=2018-12-03}}</ref> The [[C++ Standard Library]] also supports <code>for_each</code>,<ref>{{cite web|url=http://en.cppreference.com/w/cpp/algorithm/for_each |title=std::for_each - cppreference |publisher=en.cppreference.com |access-date=2017-09-30}}</ref> that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the start to the end, the range or direction can be changed by altering the first two parameters. <syntaxhighlight lang="Cpp"> #include <iostream> #include <algorithm> // contains std::for_each #include <vector> int main() { std::vector<int> v {1, 2, 3, 4, 5}; std::for_each(v.begin(), v.end(), [](int i) { std::cout << i << '\n'; }); std::cout << "reversed but skip 2 elements:\n"; std::for_each(v.rbegin()+2, v.rend(), [](int i) { std::cout << i << '\n'; }); } </syntaxhighlight> [[Qt (software)|Qt]], a C++ framework, offers a macro providing foreach loops<ref>{{cite web |url=http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword |title=Qt 4.2: Generic Containers |publisher=Doc.qt.digia.com |access-date=2013-08-04 |archive-url=https://web.archive.org/web/20151123090839/http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword |archive-date=2015-11-23 |url-status=dead }}</ref> using the STL iterator interface: <syntaxhighlight lang="Cpp"> #include <QList> #include <QDebug> int main() { QList<int> list; list << 1 << 2 << 3 << 4 << 5; foreach (int i, list) { qDebug() << i; } }</syntaxhighlight> [[Boost (C++ libraries)|Boost]], a set of free peer-reviewed portable C++ libraries also provides foreach loops:<ref>{{cite web|author=Eric Niebler |url=http://www.boost.org/doc/libs/1_53_0/doc/html/foreach.html |title=Chapter 9. Boost.Foreach - 1.53.0 |publisher=Boost.org |date=2013-01-31 |access-date=2013-08-04}}</ref> <syntaxhighlight lang="Cpp"> #include <boost/foreach.hpp> #include <iostream> int main() { int myint[] = {1, 2, 3, 4, 5}; BOOST_FOREACH(int &i, myint) { std::cout << i << '\n'; } } </syntaxhighlight> === C++/CLI === The [[C++/CLI]] language proposes a construct similar to C#. Assuming that myArray is an array of integers: <!-- At the time of writing, there is no documented C++/CLI support in the [[mw:Extension:SyntaxHighlight GeSHi|MediaWiki syntax highliter]] --> <syntaxhighlight lang="c#"> for each (int x in myArray) { Console::WriteLine(x); } </syntaxhighlight> === ColdFusion Markup Language (CFML) === {{Main|ColdFusion Markup Language}} ==== Script syntax ==== <syntaxhighlight lang="cfs"> // arrays arrayeach([1,2,3,4,5], function(v){ writeOutput(v); }); // or for (v in [1,2,3,4,5]){ writeOutput(v); } // or // (Railo only; not supported in ColdFusion) letters = ["a","b","c","d","e"]; letters.each(function(v){ writeOutput(v); // abcde }); // structs for (k in collection){ writeOutput(collection[k]); } // or structEach(collection, function(k,v){ writeOutput("key: #k#, value: #v#;"); }); // or // (Railo only; not supported in ColdFusion) collection.each(function(k,v){ writeOutput("key: #k#, value: #v#;"); }); </syntaxhighlight> ==== Tag syntax ==== <syntaxhighlight lang="CFM"> <!--- arrays ---> <cfloop index="v" array="#['a','b','c','d','e']#"> <cfoutput>#v#</cfoutput><!--- a b c d e ---> </cfloop> </syntaxhighlight> CFML incorrectly identifies the value as "index" in this construct; the <code>index</code> variable does receive the actual value of the array element, not its index. <syntaxhighlight lang="CFM"> <!--- structs ---> <cfloop item="k" collection="#collection#"> <cfoutput>#collection[k]#</cfoutput> </cfloop> </syntaxhighlight> === Common Lisp === [[Common Lisp]] provides foreach ability either with the ''dolist'' macro: <syntaxhighlight lang="LISP"> (dolist (i '(1 3 5 6 8 10 14 17)) (print i)) </syntaxhighlight> or the powerful ''loop'' macro to iterate on more data types <syntaxhighlight lang="LISP"> (loop for i in '(1 3 5 6 8 10 14 17) do (print i)) </syntaxhighlight> and even with the ''mapcar'' function: <syntaxhighlight lang="LISP"> (mapcar #'print '(1 3 5 6 8 10 14 17)) </syntaxhighlight> === D === {{Main|D (programming language)}} <syntaxhighlight lang="D"> foreach(item; set) { // do something to item } </syntaxhighlight> or <syntaxhighlight lang="D"> foreach(argument) { // pass value } </syntaxhighlight> === Dart === {{Main|Dart (programming language)}} <syntaxhighlight lang="Java"> for (final element in someCollection) { // do something with element } </syntaxhighlight> === Object Pascal, Delphi === {{Main|Object Pascal|Delphi (software)}} Foreach support was added in [[Delphi (software)|Delphi]] 2005, and uses an enumerator variable that must be declared in the ''var'' section. <syntaxhighlight lang="Delphi"> for enumerator in collection do begin //do something here end; </syntaxhighlight> === Eiffel === The iteration (foreach) form of the [[Eiffel (programming language)|Eiffel]] loop construct is introduced by the keyword <code lang=Eiffel>across</code>. In this example, every element of the structure <code>my_list</code> is printed: <syntaxhighlight lang="Eiffel"> across my_list as ic loop print (ic.item) end </syntaxhighlight> The local entity <code>ic</code> is an instance of the library class <code>ITERATION_CURSOR</code>. The cursor's feature <code>item</code> provides access to each structure element. Descendants of class <code>ITERATION_CURSOR</code> can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (<code>my_list</code> in the example) are based on classes that inherit from the library class <code>ITERABLE</code>. The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword <code>loop</code> is replaced by either <code>all</code> (effecting [[universal quantification]]) or <code>some</code> (effecting [[existential quantification]]). This iteration is a boolean expression which is true if all items in <code>my_list</code> have counts greater than three: <syntaxhighlight lang="Eiffel"> across my_list as ic all ic.item.count > 3 end </syntaxhighlight> The following is true if at least one item has a count greater than three: <syntaxhighlight lang="Eiffel"> across my_list as ic some ic.item.count > 3 end </syntaxhighlight> === Go === [[Go (programming language)|Go]]'s foreach loop can be used to loop over an array, slice, string, map, or channel. Using the two-value form gets the index/key (first element) and the value (second element): <syntaxhighlight lang="go"> for index, value := range someCollection { // Do something to index and value } </syntaxhighlight> Using the one-value form gets the index/key (first element): <syntaxhighlight lang="go"> for index := range someCollection { // Do something to index } </syntaxhighlight><ref>{{cite web | url=http://golang.org/ref/spec#RangeClause | title=Range Clause | publisher=The Go Programming Language | work=The Go Programming Language Specification | access-date=October 20, 2013}}</ref> === Groovy === [[Groovy (programming language)|Groovy]] supports ''for'' loops over collections like arrays, lists and ranges: <syntaxhighlight lang="Groovy"> 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 } </syntaxhighlight> Groovy also supports a C-style for loop with an array index: <syntaxhighlight lang="Groovy"> for (i = 0; i < x.size(); i++) { println x[i] } </syntaxhighlight> Collections in Groovy can also be iterated over using the ''each'' keyword and a closure. By default, the loop dummy is named ''it'' <syntaxhighlight lang="Groovy"> 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" </syntaxhighlight> === Haskell === [[Haskell]] allows looping over lists with [[Monad (functional programming)|monadic]] actions using <code>mapM_</code> and <code>forM_</code> (<code>mapM_</code> with its arguments flipped) from [http://hackage.haskell.org/package/base-4.6.0.1/docs/Control-Monad.html Control.Monad]: {| class="wikitable" ! code !! prints |- | <syntaxhighlight lang=Haskell> mapM_ print [1..4] </syntaxhighlight> | 1 2 3 4 |- | <syntaxhighlight lang=Haskell> forM_ "test" $ \char -> do putChar char putChar char </syntaxhighlight> | tteesstt |} It's also possible to generalize those functions to work on applicative functors rather than monads and any data structure that is traversable using <code>traverse</code> (<code>for</code> with its arguments flipped) and <code>mapM</code> (<code>forM</code> with its arguments flipped) from [http://hackage.haskell.org/package/base-4.6.0.1/docs/Data-Traversable.html Data.Traversable]. === Haxe === {{Main|Haxe}} <syntaxhighlight lang="actionscript"> for (value in iterable) { trace(value); } Lambda.iter(iterable, function(value) trace(value)); </syntaxhighlight> === Java === In [[Java (programming language)|Java]], a foreach-construct was introduced in [[Java Development Kit]] (JDK) 1.5.0.<ref name="jdk5release"> "Enhanced for Loop - This new language construct[...]" {{cite web |url=http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html |title=Java Programming Language, Section: Enhancements in JDK 5 |access-date=2009-05-26 |year=2004 |publisher=[[Sun Microsystems, Inc.]] }}</ref> Official sources use several names for the construct. It is referred to as the "Enhanced for Loop",<ref name="jdk5release"/> the "For-Each Loop",<ref> "The For-Each Loop" {{cite web |url=http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html |title=The For-Each Loop |access-date=2009-05-10 |year=2008 |publisher=[[Sun Microsystems, Inc.]] }}</ref> and the "foreach statement".<ref> "Implementing this interface allows an object to be the target of the "foreach" statement." {{cite web |url=http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html |title=Iterable (Java Platform SE 6) |access-date=2009-05-12 |year=2004 |publisher=[[Sun Microsystems, Inc.]] }}</ref><ref name=Bloch>{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}</ref>{{rp|264}} <syntaxhighlight lang="Java"> for (Type item : iterableCollection) { // Do something to item } </syntaxhighlight> Java also provides the stream api since java 8:<ref name=Bloch>{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}</ref>{{rp|294-203}} <syntaxhighlight lang="Java"> List<Integer> intList = List.of(1, 2, 3, 4); intList.stream().forEach(i -> System.out.println(i)); </syntaxhighlight> === JavaScript === In [[ECMAScript 5]], a callback-based <code>forEach()</code> method was added to the array [[Prototype-based programming|prototype]]:<ref>{{Cite web |date=2024-07-25 |title=Array.prototype.forEach() - JavaScript {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach |access-date=2024-12-03 |website=developer.mozilla.org |language=en-US}}</ref><syntaxhighlight lang="javascript"> myArray.forEach(function (item, index) { // Do stuff with item and index // The index variable can be omitted from the parameter list if not needed }); </syntaxhighlight>The [[ECMAScript 6]] standard introduced a more conventional <code>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of for..of]</code> syntax that works on all [[Iterator|iterables]] rather than operating on only array instances. However, no index variable is available with the syntax. <syntaxhighlight lang="javascript"> for (const item of myArray) { // Do stuff with item } </syntaxhighlight> For unordered iteration over the keys in an object, [[JavaScript]] features the <code>for..in</code> loop: <syntaxhighlight lang="javascript"> for (const key in myObject) { // Do stuff with myObject[key] } </syntaxhighlight> To limit the iteration to the object's own properties, excluding those inherited through the prototype chain, it's often useful to add a <code>hasOwnProperty()</code> test (or a <code>hasOwn()</code> test if supported).<ref>{{Cite web |date=2023-09-25 |title=Object.hasOwn() - JavaScript {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#description |access-date=2024-12-03 |website=developer.mozilla.org |language=en-US}}</ref> <syntaxhighlight lang="javascript">for (const key in myObject) { // Available in older browsers if (myObject.hasOwnProperty(key)) { // Do stuff with object[key] } // Preferred in modern browsers if (Object.hasOwn(myObject, key)) { // Do stuff with object[key] } }</syntaxhighlight> Alternatively, the <code>Object.keys()</code> method combined with the <code>for..of</code> loop can be used for a less verbose way to iterate over the keys of an object.<ref>{{cite web | url= https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys | title=Object.keys | work=Mozilla Developer Network | access-date=May 7, 2014}}</ref> <syntaxhighlight lang="javascript"> const book = { name: "A Christmas Carol", author: "Charles Dickens" }; for (const key of Object.keys(book)) { console.log(`Key: ${key}, Value: ${book[key]}`); } </syntaxhighlight> === Lua === {{Main|Lua (programming language)}} Source:<ref>{{Cite web|url=https://en.wikibooks.org/wiki/Lua_Programming/Tables#Foreach_loop|title=Lua Programming/Tables - Wikibooks, open books for an open world|website=en.wikibooks.org|language=en|access-date=2017-12-06}}</ref> Iterate only through numerical index values:<syntaxhighlight lang="lua"> for index, value in ipairs(array) do -- do something end </syntaxhighlight>Iterate through all index values:<syntaxhighlight lang="lua"> for index, value in pairs(array) do -- do something end </syntaxhighlight> === Mathematica === In [[Mathematica]], <code>Do</code> will simply evaluate an expression for each element of a list, without returning any value. <syntaxhighlight lang="Mathematica"> In[]:= Do[doSomethingWithItem, {item, list}] </syntaxhighlight> It is more common to use <code>Table</code>, which returns the result of each evaluation in a new list. <syntaxhighlight lang="Mathematica"> In[]:= list = {3, 4, 5}; In[]:= Table[item^2, {item, list}] Out[]= {9, 16, 25} </syntaxhighlight> === MATLAB === {{Main|MATLAB}} <syntaxhighlight lang="MATLAB"> for item = array %do something end </syntaxhighlight> === Mint === For each loops are supported in Mint, possessing the following syntax: <syntaxhighlight lang="Ruby"> for each element of list /* 'Do something.' */ end </syntaxhighlight> The <code>for (;;)</code> or <code>while (true)</code> [[infinite loop]] in Mint can be written using a for each loop and an [[Infinite set|infinitely long list]].<ref>{{cite web |url=http://prezi.com/ougvv1wzx2lb/mint-tutorial-part-0/ |title=Mint Tutorial |access-date=20 October 2013 |author=Chu, Oliver}}</ref> <syntaxhighlight lang="Ruby"> import type /* 'This function is mapped to' * 'each index number i of the' * 'infinitely long list.' */ sub identity(x) return x end /* 'The following creates the list' * '[0, 1, 2, 3, 4, 5, ..., infinity]' */ infiniteList = list(identity) for each element of infiniteList /* 'Do something forever.' */ end </syntaxhighlight> === Objective-C === Foreach loops, called [[Objective-C#Fast enumeration|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. <syntaxhighlight lang="ObjC"> NSArray *a = [NSArray new]; // Any container class can be substituted for(id obj in a) { // Dynamic typing is used. The type of object stored // in 'a' can be unknown. The array can hold many different // types of object. printf("%s\n", [[obj description] UTF8String]); // Must use UTF8String with %s NSLog(@"%@", obj); // Leave as an object } </syntaxhighlight> NSArrays can also broadcast a message to their members: <syntaxhighlight lang="ObjC"> NSArray *a = [NSArray new]; [a makeObjectsPerformSelector:@selector(printDescription)]; </syntaxhighlight> Where [[Blocks (C language extension)|blocks]] are available, an NSArray can automatically perform a block on every contained item: <syntaxhighlight lang="ObjC"> [myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"obj %@", obj); if ([obj shouldStopIterationNow]) *stop = YES; }]; </syntaxhighlight> The type of collection being iterated will dictate the item returned with each iteration. For example: <syntaxhighlight lang="ObjC"> NSDictionary *d = [NSDictionary new]; for(id key in d) { NSObject *obj = [d objectForKey:key]; // We use the (unique) key to access the (possibly nonunique) object. NSLog(@"%@", obj); } </syntaxhighlight> === OCaml === [[OCaml]] is a [[functional programming]] language. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays. For lists: <syntaxhighlight lang="OCaml"> List.iter (fun x -> print_int x) [1;2;3;4];; </syntaxhighlight> or in short way: <syntaxhighlight lang="OCaml"> List.iter print_int [1;2;3;4];; </syntaxhighlight> For arrays: <syntaxhighlight lang="OCaml"> Array.iter (fun x -> print_int x) [|1;2;3;4|];; </syntaxhighlight> or in short way: <syntaxhighlight lang="OCaml"> Array.iter print_int [|1;2;3;4|];; </syntaxhighlight> === ParaSail === The [[ParaSail (programming language)|ParaSail]] parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container: <syntaxhighlight lang="parasail"> var Con : Container<Element_Type> := ... // ... for each Elem of Con concurrent loop // loop may also be "forward" or "reverse" or unordered (the default) // ... do something with Elem end loop </syntaxhighlight> 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": <syntaxhighlight lang="parasail"> var My_Map : Map<Key_Type => Univ_String, Value_Type => Tree<Integer>> := ... const My_Set : Set<Univ_String> := ["abc", "def", "ghi"]; for each [Str => Tr] of My_Map {Str in My_Set} forward loop // ... do something with Str or Tr end loop </syntaxhighlight> === Pascal === In [[Pascal (programming language)|Pascal]], ISO standard 10206:1990 introduced iteration over [[Pascal (programming language)#Set types|set types]], thus: <syntaxhighlight lang="Pascal"> var elt: ElementType; eltset: set of ElementType; {...} for elt in eltset do { ... do something with elt } </syntaxhighlight> === Perl === 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: <syntaxhighlight lang="Perl"> foreach (1, 2, 3, 4) { print $_; } </syntaxhighlight> Array examples: <syntaxhighlight lang="Perl"> foreach (@arr) { print $_; } </syntaxhighlight> <syntaxhighlight lang="Perl"> foreach $x (@arr) { #$x is the element in @arr print $x; } </syntaxhighlight> Hash example: <syntaxhighlight lang="Perl"> foreach $x (keys %hash) { print $x . " = " . $hash{$x}; # $x is a key in %hash and $hash{$x} is its value } </syntaxhighlight> Direct modification of collection members: <syntaxhighlight lang="Perl"> @arr = ( 'remove-foo', 'remove-bar' ); foreach $x (@arr){ $x =~ s/remove-//; } # Now @arr = ('foo', 'bar'); </syntaxhighlight> === PHP === {{Main|PHP syntax and semantics}} <syntaxhighlight lang="php"> foreach ($set as $value) { // Do something to $value; } </syntaxhighlight> It is also possible to extract both keys and values using the alternate syntax: <syntaxhighlight lang="php"> foreach ($set as $key => $value) { echo "{$key} has a value of {$value}"; } </syntaxhighlight> Direct modification of collection members: <syntaxhighlight lang="php"> $arr = array(1, 2, 3); foreach ($arr as &$value) { // The &, $value is a reference to the original value inside $arr $value++; } // Now $arr = array(2, 3, 4); // also works with the full syntax foreach ($arr as $key => &$value) { $value++; } </syntaxhighlight> * [https://php.net/foreach More information] === Python === {{Main|Python (programming language)}} <syntaxhighlight lang="python"> for item in iterable_collection: # Do something with item </syntaxhighlight> Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in [[Associative array|dictionaries]]: <syntaxhighlight lang="python"> for key, value in some_dict.items(): # Direct iteration on a dict iterates on its keys # Do stuff </syntaxhighlight> As <code>for ... in</code> is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is... <syntaxhighlight lang="python"> for i in range(len(seq)): # Do something to seq[i] </syntaxhighlight> ... although using the <code>enumerate</code> function is considered more "Pythonic": <syntaxhighlight lang="python"> for i, item in enumerate(seq): # Do stuff with item # Possibly assign it back to seq[i] </syntaxhighlight> === R === {{Main|R (programming language)}} <syntaxhighlight lang="R"> for (item in object) { # Do something with item } </syntaxhighlight> As <code>for ... in</code> is the only kind of <code>for</code> loop in R, the equivalent to the "counter" loop found in other languages is... <syntaxhighlight lang="R"> for (i in seq_along(object)) { # Do something with object[[i]] } </syntaxhighlight> === Racket === {{Main|Racket (programming language)}} <syntaxhighlight lang="racket"> (for ([item set]) (do-something-with item)) </syntaxhighlight> or using the conventional Scheme <code>for-each</code> function: <syntaxhighlight lang="racket"> (for-each do-something-with a-list) </syntaxhighlight> <code>do-something-with</code> is a one-argument function. === Raku === In [[Raku (programming language)|Raku]], a sister language to Perl, ''for'' must be used to traverse elements of a list (''foreach'' is not 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). List literal example: <syntaxhighlight lang="Perl6"> for 1..4 { .say; } </syntaxhighlight> Array examples: <syntaxhighlight lang="Perl6"> for @arr { .say; } </syntaxhighlight> The for loop in its statement modifier form: <syntaxhighlight lang="Perl6"> .say for @arr; </syntaxhighlight> <syntaxhighlight lang="Perl6"> for @arr -> $x { say $x; } </syntaxhighlight> <syntaxhighlight lang="Perl6"> for @arr -> $x, $y { # more than one item at a time say "$x, $y"; } </syntaxhighlight> Hash example: <syntaxhighlight lang="Perl6"> for keys %hash -> $key { say "$key: $hash{$key}"; } </syntaxhighlight> or <syntaxhighlight lang="Perl6"> for %hash.kv -> $key, $value { say "$key: $value"; } </syntaxhighlight> or <syntaxhighlight lang="Perl6"> for %hash -> $x { say "$x.key(): $x.value()"; # Parentheses needed to inline in double quoted string } </syntaxhighlight> Direct modification of collection members with a doubly pointy block, ''<->'': <syntaxhighlight lang="Perl6"> my @arr = 1,2,3; for @arr <-> $x { $x *= 2; } # Now @arr = 2,4,6; </syntaxhighlight> === Ruby === {{Main|Ruby (programming language)}} <syntaxhighlight lang="Ruby"> set.each do |item| # do something to item end </syntaxhighlight> or <syntaxhighlight lang="Ruby"> for item in set # do something to item end </syntaxhighlight> This can also be used with a hash. <syntaxhighlight lang="Ruby"> set.each do |key,value| # do something to key # do something to value end </syntaxhighlight> === Rust === {{Main|Rust (programming language)}} The <code>for</code> loop has the structure <syntaxhighlight lang="rust" inline>for <pattern> in <expression> { /* optional statements */ }</syntaxhighlight>. It implicitly calls the [https://doc.rust-lang.org/std/iter/trait.IntoIterator.html <code>IntoIterator::into_iter</code>] method on the expression, and uses the resulting value, which must implement the [https://doc.rust-lang.org/std/iter/trait.Iterator.html <code>Iterator</code>] trait. If the expression is itself an iterator, it is used directly by the <code>for</code> loop through an [https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#impl-IntoIterator-25 implementation of <code>IntoIterator</code> for all <code>Iterator</code>s] that returns the iterator unchanged. The loop calls the <code>Iterator::next</code> method on the iterator before executing the loop body. If <code>Iterator::next</code> returns <code>[[option type|Some(_)]]</code>, the value inside is assigned to the [[pattern matching|pattern]] and the loop body is executed; if it returns <code>None</code>, the loop is terminated. <syntaxhighlight lang="Rust"> let mut numbers = vec![1, 2, 3]; // Immutable reference: for number in &numbers { // calls IntoIterator::into_iter(&numbers) println!("{}", number); } for square in numbers.iter().map(|x| x * x) { // numbers.iter().map(|x| x * x) implements Iterator println!("{}", square); } // Mutable reference: for number in &mut numbers { // calls IntoIterator::into_iter(&mut numbers) *number *= 2; } // prints "[2, 4, 6]": println!("{:?}", numbers); // Consumes the Vec and creates an Iterator: for number in numbers { // calls IntoIterator::into_iter(numbers) // ... } // Errors with "borrow of moved value": // println!("{:?}", numbers); </syntaxhighlight> === Scala === {{Main|Scala (programming language)}} <syntaxhighlight lang="Scala"> // return list of modified elements items map { x => doSomething(x) } items map multiplyByTwo for {x <- items} yield doSomething(x) for {x <- items} yield multiplyByTwo(x) // return nothing, just perform action items foreach { x => doSomething(x) } items foreach println for {x <- items} doSomething(x) for {x <- items} println(x) // pattern matching example in for-comprehension for ((key, value) <- someMap) println(s"$key -> $value") </syntaxhighlight> === Scheme === {{Main|Scheme (programming language)}} <syntaxhighlight lang="Scheme"> (for-each do-something-with a-list) </syntaxhighlight> <code>do-something-with</code> is a one-argument function. === Smalltalk === {{Main|Smalltalk}} <syntaxhighlight lang="Smalltalk"> collection do: [:item| "do something to item" ] </syntaxhighlight> === Swift === [[Swift (programming language)|Swift]] uses the <code>for</code>…<code>in</code> construct to iterate over members of a collection.<ref>{{Cite web|url=https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_153|title=Control Flow — the Swift Programming Language (Swift 5.5)}}</ref> <syntaxhighlight lang="objc"> for thing in someCollection { // do something with thing } </syntaxhighlight> The <code>for</code>…<code>in</code> loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times. <syntaxhighlight lang="objc"> for i in 0..<10 { // 0..<10 constructs a half-open range, so the loop body // is repeated for i = 0, i = 1, …, i = 9. } for i in 0...10 { // 0...10 constructs a closed range, so the loop body // is repeated for i = 0, i = 1, …, i = 9, i = 10. } </syntaxhighlight> === SystemVerilog === [[SystemVerilog]] supports iteration over any vector or array type of any dimensionality using the <code>foreach</code> keyword. A trivial example iterates over an array of integers: {| class="wikitable" ! code !! prints |- | <syntaxhighlight lang="systemverilog"> int array_1d[] = '{ 3, 2, 1, 0 }; foreach array_1d[index] $display("array_1d[%0d]: %0d", index, array_1d[index]); </syntaxhighlight> | array_1d[0]: 3 array_1d[1]: 2 array_1d[2]: 1 array_1d[3]: 0 |} A more complex example iterates over an associative array of arrays of integers: {| class="wikitable" ! code !! prints |- | <syntaxhighlight lang="systemverilog"> int array_2d[string][] = '{ "tens": '{ 10, 11 }, "twenties": '{ 20, 21 } }; foreach array_2d[key,index] $display("array_2d[%s,%0d]: %0d", key, index, array_2d[key,index]); </syntaxhighlight> | array_2d[tens,0]: 10 array_2d[tens,1]: 11 array_2d[twenties,0]: 20 array_2d[twenties,1]: 21 |} === Tcl === [[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. {| class="wikitable" ! code !! prints |- | <syntaxhighlight lang=Tcl> foreach {i j} {1 2 3 4 5 6} { puts "$i $j" } </syntaxhighlight> | 1 2 3 4 5 6 |} It is also possible to iterate over more than one list simultaneously. In the following <code>i</code> assumes sequential values of the first list, <code>j</code> sequential values of the second list: {| class="wikitable" ! code !! prints |- | <syntaxhighlight lang=Tcl> foreach i {1 2 3} j {a b c} { puts "$i $j" } </syntaxhighlight> | 1 a 2 b 3 c |} === Visual Basic (.NET) === {{Main|Visual Basic (.NET)}} <syntaxhighlight lang="VBNet"> For Each item In enumerable ' Do something with item. Next </syntaxhighlight> or without [[type inference]] <syntaxhighlight lang="VBNet"> For Each item As type In enumerable ' Do something with item. Next </syntaxhighlight> === Windows === ==== Conventional command processor ==== {{main|COMMAND.COM|cmd.exe}} Invoke a hypothetical <code>frob</code> command three times, giving it a color name each time. <syntaxhighlight lang="doscon"> C:\>FOR %%a IN ( red green blue ) DO frob %%a </syntaxhighlight> ==== Windows PowerShell ==== {{Main|Windows PowerShell}} <syntaxhighlight lang="PowerShell"> foreach ($item in $set) { # Do something to $item } </syntaxhighlight> From a pipeline <syntaxhighlight lang="PowerShell"> $list | ForEach-Object {Write-Host $_} # or using the aliases $list | foreach {write $_} $list | % {write $_} </syntaxhighlight> === XSLT === {{Main|XSLT}} <syntaxhighlight lang="xml"> <xsl:for-each select="set"> <!-- do something for the elements in <set> --> </xsl:for-each> </syntaxhighlight><ref name="xslforeach">{{cite web | url=https://www.w3schools.com/xsl/xsl_for_each.asp | title=XSLT <xsl:for-each> Element | work=W3Schools.com}}</ref> == See also == * [[Do while loop]] * [[For loop]] * [[While loop]] * [[Map (higher-order function)]] == References == {{Reflist|2}} [[Category:Control flow]] [[Category:Iteration in programming]] [[Category:Programming language comparisons]] <!-- Hidden categories below --> [[Category:Articles with example Ada code]] [[Category:Articles with example C code]] [[Category:Articles with example C++ code]] [[Category:Articles with example C Sharp code]] [[Category:Articles with example D code]] [[Category:Articles with example Eiffel code]] [[Category:Articles with example Haskell code]] [[Category:Articles with example Java code]] [[Category:Articles with example JavaScript code]] [[Category:Articles with example Lisp (programming language) code]] [[Category:Articles with example MATLAB/Octave code]] [[Category:Articles with example Objective-C code]] [[Category:Articles with example OCaml code]] [[Category:Articles with example Pascal code]] [[Category:Articles with example Perl code]] [[Category:Articles with example PHP code]] [[Category:Articles with example Python (programming language) code]] [[Category:Articles with example R code]] [[Category:Articles with example Racket code]] [[Category:Articles with example Ruby code]] [[Category:Articles with example Rust code]] [[Category:Articles with example Scala code]] [[Category:Articles with example Scheme (programming language) code]] [[Category:Articles with example Smalltalk code]] [[Category:Articles with example Swift code]] [[Category:Articles with example Tcl code]] [[ru:Цикл просмотра]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite web
(
edit
)
Template:Code
(
edit
)
Template:For
(
edit
)
Template:Loop constructs
(
edit
)
Template:Main
(
edit
)
Template:Mono
(
edit
)
Template:Reflist
(
edit
)
Template:Rp
(
edit
)
Template:Short description
(
edit
)
Template:Sister project
(
edit
)
Template:Wikibooks
(
edit
)