Foreach loop: Difference between revisions

From HandWiki
(link)
 
(url)
 
Line 1: Line 1:
{{Short description|Control flow statement for traversing items in a collection}}
{{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.]]
[[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}}<!-- NOTE: Please don't remove. Discuss navigation concept at [[Talk:Do_while_loop#Helpbox_experiment] -->
{{Loop constructs}}<!-- DO NOT remove. Discuss navigation concept at Talk:Do while loop#Helpbox experiment -->


In [[Computer programming|computer programming]], '''foreach loop''' (or '''for-each loop''') is a [[Control flow|control flow]] statement for traversing items in a 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
In [[Computer programming|computer programming]], '''foreach loop''' (or '''for-each loop''') is a [[Control flow|control flow]] statement for traversing items in a 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
Line 14: Line 15:


== Syntax ==
== Syntax ==
Syntax varies among languages. Most use the simple word <code>for</code>, roughly as follows:
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:


  for each item in collection:
  foreach(key, value) in collection {
   do something to item
   # Do something to value #
}


== Language support ==
== 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), [[Software:Delphi|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]], [[Organization:PHP|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]], [[Software:Tcsh|tcsh]], [[Unix shell]]s, [[Visual Basic (.NET)]], and Windows PowerShell. Notable languages without foreach are [[C (programming language)|C]], and C++ pre-C++11.
[[Programming language]]s which support foreach loops include [[ABC (programming language)|ABC]], [[ActionScript]], [[Ada (programming language)|Ada]], [[C++11]], [[C Sharp (programming language)|C#]], [[ColdFusion Markup Language]] (CFML), [[Cobra (programming language)|Cobra]], [[D (programming language)|D]], [[Daplex]] (query language), [[Software:Delphi|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]], [[Organization:PHP|PHP]], [[Prolog]],<ref>{{Cite web|url=https://www.swi-prolog.org/pldoc/man?predicate=foreach/2|title=SWI-Prolog -- foreach/2|website=www.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}}</ref> [[Red (programming language)|Red]],<ref>{{Cite web|url=http://www.red-lang.org}}</ref> [[Ruby (programming language)|Ruby]], [[Scala (programming language)|Scala]], [[Smalltalk]], [[Swift (programming language)|Swift]], [[Tcl]], [[Software:Tcsh|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 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.
[[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.


<source lang="actionscript3">
<syntaxhighlight lang="actionscript3">
var foo:Object = {
var foo:Object = {
"apple":1,
"apple":1,
Line 38: Line 38:


// returns "1" then "2"
// returns "1" then "2"
</source>
</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.
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.


<source lang="actionscript3">
<syntaxhighlight lang="actionscript3">
for (var key:String in foo) {  
for (var key:String in foo) {  
trace(key);  
trace(key);  
Line 48: Line 48:


// returns "apple" then "orange"
// returns "apple" then "orange"
</source>
</syntaxhighlight>


=== Ada ===
=== Ada ===
 
{{Wikibooks|Ada Programming|Control}}
[[Ada (programming language)|Ada]] supports foreach loops as part of the normal [[For loop|for loop]]. Say X is an [[Array data structure|array]]:
[[Ada (programming language)|Ada]] supports foreach loops as part of the normal [[For loop|for loop]]. Say X is an [[Array data structure|array]]:


<source lang="Ada">
<syntaxhighlight lang="Ada">
for I in X'Range loop
for I in X'Range loop
   X (I) := Get_Next_Element;
   X (I) := Get_Next_Element;
end loop;
end loop;
</source>
</syntaxhighlight>


This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed.
This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed.
Line 64: Line 64:
Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...):
Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...):


<source lang="Ada">
<syntaxhighlight lang="Ada">
for Obj of X loop
for Obj of X loop
   -- Work on Obj
   -- Work on Obj
end loop;
end loop;
</source>
</syntaxhighlight>


=== C ===
=== C ===
Line 78: Line 78:


C string as a collection of char
C string as a collection of char
<source lang="c" highlight="4-6" line>
<syntaxhighlight lang="c" highlight="4-6" line>
#include <stdio.h>
#include <stdio.h>


Line 97: Line 97:
  return 0;
  return 0;
}
}
</source>
</syntaxhighlight>


C int array as a collection of int (array size known at compile-time)
C int array as a collection of int (array size known at compile-time)
<source lang="c" highlight="4-6" line>
<syntaxhighlight lang="c" highlight="4-6" line>
#include <stdio.h>
#include <stdio.h>


Line 119: Line 119:
  return 0;
  return 0;
}
}
</source>
</syntaxhighlight>


Most general: string or array as collection (collection size known at run-time)
Most general: string or array as collection (collection size known at run-time)
: ''Note: {{code|idxtype}} can be removed and <code>[[Typeof|typeof]](col[0])</code> used in its place with [[Software:GNU Compiler Collection|GCC]]''
: ''{{code|idxtype}} can be removed and <code>[[Typeof|typeof]](col[0])</code> used in its place with [[Software:GNU Compiler Collection|GCC]]''
<source lang="c" highlight="5-8" line>
<syntaxhighlight lang="c" highlight="5-8" line>
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
Line 152: Line 152:
  return 0;
  return 0;
}
}
</source>
</syntaxhighlight>


=== C# ===
=== C# ===
In [[C Sharp (programming language)|C#]], assuming that myArray is an array of integers:
In [[C Sharp (programming language)|C#]], assuming that myArray is an array of integers:


<source lang="csharp">
<syntaxhighlight lang="csharp">


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


</source>
</syntaxhighlight>


[[Language Integrated Query]] (LINQ) provides the following syntax, accepting a [[Delegate (CLI)|delegate]] or lambda expression:
[[Language Integrated Query]] (LINQ) provides the following syntax, accepting a [[Delegate (CLI)|delegate]] or lambda expression:


<source lang="csharp">
<syntaxhighlight lang="csharp">


myArray.ToList().ForEach(x => Console.WriteLine(x));
myArray.ToList().ForEach(x => Console.WriteLine(x));


</source>
</syntaxhighlight>


=== C++ ===
=== C++ ===
[[C++11]] provides a foreach loop. The syntax is similar to that of [[Foreach loop#Java|Java]]:
[[C++11]] provides a foreach loop. The syntax is similar to that of [[Foreach loop#Java|Java]]:


<source lang="Cpp">
<syntaxhighlight lang="Cpp">
#include <iostream>
#include <iostream>


Line 187: Line 186:
   }
   }
}
}
</source>
</syntaxhighlight>


C++11 range-based for statements have been implemented in [[Software:GNU Compiler Collection|GNU Compiler Collection]] (GCC) (since version 4.6), [[Software:Clang|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>)
C++11 range-based for statements have been implemented in [[Software:GNU Compiler Collection|GNU Compiler Collection]] (GCC) (since version 4.6), [[Software:Clang|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>)
Line 193: Line 192:
The range-based <code>for</code> is [[Syntactic sugar|syntactic sugar]] equivalent to:
The range-based <code>for</code> is [[Syntactic sugar|syntactic sugar]] equivalent to:


<source lang="Cpp">
<syntaxhighlight lang="Cpp">
   for (auto __anon = begin(myint); __anon != end(myint); ++__anon)
   for (auto __anon = begin(myint); __anon != end(myint); ++__anon)
   {
   {
Line 199: Line 198:
     std::cout << i << '\n';
     std::cout << i << '\n';
   }
   }
</source>
</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 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 [[Software:C++ Standard Library|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 beginning to the end, the range and direction you can change the direction or range by altering the first two parameters.
The [[Software:C++ Standard Library|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.


<source lang="Cpp">
<syntaxhighlight lang="Cpp">
#include <iostream>
#include <iostream>
#include <algorithm> // contains std::for_each
#include <algorithm> // contains std::for_each
Line 226: Line 225:
   });
   });
}
}
</source>
</syntaxhighlight>


[[Software:Qt|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:
[[Software:Qt|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:


<source lang="Cpp">
<syntaxhighlight lang="Cpp">
#include <QList>
#include <QList>
#include <QDebug>
#include <QDebug>
Line 244: Line 243:
     qDebug() << i;
     qDebug() << i;
   }
   }
}</source>
}</syntaxhighlight>


[[Software: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>
[[Software: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>


<source lang="Cpp">
<syntaxhighlight lang="Cpp">
#include <boost/foreach.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <iostream>
Line 261: Line 260:
   }
   }
}
}
</source>
</syntaxhighlight>


=== C++/CLI ===
=== C++/CLI ===
The C++/CLI language proposes a construct similar to C#.
The C++/CLI language proposes a construct similar to C#.


Assuming that myArray is an array of integers:
Assuming that myArray is an array of integers:
<!-- At the time of writing, there is no documented C++/CLI support in the MediaWiki syntax highliter -->
<!-- At the time of writing, there is no documented C++/CLI support in the MediaWiki syntax highliter -->
<source lang="c#">
<syntaxhighlight lang="c#">
for each (int x in myArray)
for each (int x in myArray)
{
{
     Console::WriteLine(x);
     Console::WriteLine(x);
}
}
</source>
</syntaxhighlight>


=== ColdFusion Markup Language (CFML) ===
=== ColdFusion Markup Language (CFML) ===
Line 280: Line 278:


==== Script syntax ====
==== Script syntax ====
 
<syntaxhighlight lang="cfs">
<source lang="cfs">
// arrays
// arrays
arrayeach([1,2,3,4,5], function(v){
arrayeach([1,2,3,4,5], function(v){
Line 317: Line 314:
     writeOutput("key: #k#, value: #v#;");
     writeOutput("key: #k#, value: #v#;");
});
});
</source>
</syntaxhighlight>


==== Tag syntax ====
==== Tag syntax ====
 
<syntaxhighlight lang="CFM">
<source lang="CFM">
<!--- arrays --->
<!--- arrays --->
<cfloop index="v" array="#['a','b','c','d','e']#">
<cfloop index="v" array="#['a','b','c','d','e']#">
   <cfoutput>#v#</cfoutput><!--- a b c d e  --->
   <cfoutput>#v#</cfoutput><!--- a b c d e  --->
</cfloop>
</cfloop>
</source>
</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.
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.


<source lang="CFM">
<syntaxhighlight lang="CFM">
<!--- structs --->
<!--- structs --->
<cfloop item="k" collection="#collection#">
<cfloop item="k" collection="#collection#">
     <cfoutput>#collection[k]#</cfoutput>
     <cfoutput>#collection[k]#</cfoutput>
</cfloop>
</cfloop>
</source>
</syntaxhighlight>


=== Common Lisp ===
=== Common Lisp ===
[[Common Lisp]] provides foreach ability either with the ''dolist'' macro:
[[Common Lisp]] provides foreach ability either with the ''dolist'' macro:
<source lang="LISP">
<syntaxhighlight lang="LISP">
(dolist (i '(1 3 5 6 8 10 14 17))
(dolist (i '(1 3 5 6 8 10 14 17))
   (print i))
   (print i))
</source>
</syntaxhighlight>
or the powerful ''loop'' macro to iterate on more data types
or the powerful ''loop'' macro to iterate on more data types
<source lang="LISP">
<syntaxhighlight lang="LISP">
(loop for i in '(1 3 5 6 8 10 14 17)
(loop for i in '(1 3 5 6 8 10 14 17)
       do (print i))
       do (print i))
</source>
</syntaxhighlight>


and even with the ''mapcar'' function:
and even with the ''mapcar'' function:
<source lang="LISP">
<syntaxhighlight lang="LISP">
(mapcar #'print '(1 3 5 6 8 10 14 17))
(mapcar #'print '(1 3 5 6 8 10 14 17))
</source>
</syntaxhighlight>


=== D ===
=== D ===
{{Main|D (programming language)}}
{{Main|D (programming language)}}
 
<syntaxhighlight lang="D">
<source lang="D">
foreach(item; set) {
foreach(item; set) {
   // do something to item
   // do something to item
}
}
</source>
</syntaxhighlight>


or
or


<source lang="D">
<syntaxhighlight lang="D">
foreach(argument) {
foreach(argument) {
   // pass value
   // pass value
}
}
</source>
</syntaxhighlight>


=== Dart ===
=== Dart ===
{{Main|Dart (programming language)}}
{{Main|Dart (programming language)}}
 
<syntaxhighlight lang="Java">
<source lang="Java">
for (final element in someCollection) {
for (final element in someCollection) {
   // do something with element
   // do something with element
}
}
</source>
</syntaxhighlight>


=== Object Pascal, Delphi ===
=== Object Pascal, Delphi ===
{{Main|Object Pascal}}
{{Main|Object Pascal|Delphi (software)}}
 
Foreach support was added in [[Software:Delphi|Delphi]] 2005, and uses an enumerator variable that must be declared in the ''var'' section.
Foreach support was added in [[Delphi (programming language)|Delphi]] 2005, and uses an enumerator variable that must be declared in the ''var'' section.


<source lang="Delphi">
<syntaxhighlight lang="Delphi">
for enumerator in collection do
for enumerator in collection do
begin
begin
   //do something here
   //do something here
end;
end;
</source>
</syntaxhighlight>


=== Eiffel ===
=== Eiffel ===
The iteration (foreach) form of the [[Eiffel (programming language)|Eiffel]] loop construct is introduced by the keyword <code lang=Eiffel>across</code>.
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:
In this example, every element of the structure <code>my_list</code> is printed:


<source lang="Eiffel">
<syntaxhighlight lang="Eiffel">
             across my_list as ic loop print (ic.item) end
             across my_list as ic loop print (ic.item) end
</source>
</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 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>.
Line 408: Line 399:
This iteration is a boolean expression which is true if all items in <code>my_list</code> have counts greater than three:
This iteration is a boolean expression which is true if all items in <code>my_list</code> have counts greater than three:


<source lang="Eiffel">
<syntaxhighlight lang="Eiffel">
             across my_list as ic all ic.item.count > 3 end
             across my_list as ic all ic.item.count > 3 end
</source>
</syntaxhighlight>


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


<source lang="Eiffel">
<syntaxhighlight lang="Eiffel">
             across my_list as ic some ic.item.count > 3 end
             across my_list as ic some ic.item.count > 3 end
</source>
</syntaxhighlight>


=== Go ===
=== Go ===
[[Go (programming language)|Go]]'s foreach loop can be used to loop over an array, slice, string, map, or channel.
[[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, we get the index/key (first element) and the value (second element):
Using the two-value form gets the index/key (first element) and the value (second element):
<source lang="go">
<syntaxhighlight lang="go">
for index, value := range someCollection {
for index, value := range someCollection {
// Do something to index and value
// Do something to index and value
}
}
</source>
</syntaxhighlight>


Using the one-value form, we get the index/key (first element):
Using the one-value form gets the index/key (first element):
<source lang="go">
<syntaxhighlight lang="go">
for index := range someCollection {
for index := range someCollection {
// Do something to index
// Do something to index
}
}
</source><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>
</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 ===
[[Groovy (programming language)|Groovy]] supports ''for'' loops over collections like arrays, lists and ranges:


Groovy supports ''for'' loops over collections like arrays, lists and ranges:
<syntaxhighlight lang="Groovy">
 
<source lang="Groovy">
def x = [1,2,3,4]
def x = [1,2,3,4]
for (v in x)          // loop over the 4-element array x
for (v in x)          // loop over the 4-element array x
Line 456: Line 445:
     println v
     println v
}
}
</source>
</syntaxhighlight>


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


<source lang="Groovy">
<syntaxhighlight lang="Groovy">
for (i = 0; i < x.size(); i++)
for (i = 0; i < x.size(); i++)
{
{
     println x[i]
     println x[i]
}
}
</source>
</syntaxhighlight>


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


<source lang="Groovy">
<syntaxhighlight lang="Groovy">
x.each{ println it }    // print every element of the x array
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"
x.each{i-> println i}    // equivalent to line above, only loop dummy explicitly named "i"
</source>
</syntaxhighlight>


=== Haskell ===
=== 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]:
[[Haskell (programming language)|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"
{| class="wikitable"
Line 483: Line 471:
|-
|-
|
|
<source lang=Haskell>
<syntaxhighlight lang=Haskell>
mapM_ print [1..4]
mapM_ print [1..4]
</source>
</syntaxhighlight>
|
|
  1
  1
Line 493: Line 481:
|-
|-
|
|
<source lang=Haskell>
<syntaxhighlight lang=Haskell>
forM_ "test" $ \char -> do  
forM_ "test" $ \char -> do  
     putChar char
     putChar char
     putChar char
     putChar char
</source>
</syntaxhighlight>
|
|
  tteesstt
  tteesstt
Line 506: Line 494:
=== Haxe ===
=== Haxe ===
{{Main|Haxe}}
{{Main|Haxe}}
<source lang="actionscript">
<syntaxhighlight lang="actionscript">
for (value in iterable) {
for (value in iterable) {
     trace(value);
     trace(value);
Line 512: Line 500:


Lambda.iter(iterable, function(value) trace(value));
Lambda.iter(iterable, function(value) trace(value));
</source>
</syntaxhighlight>


=== Java ===
=== Java ===
In [[Java (programming language)|Java]], a foreach-construct was introduced in [[Software:Java Development Kit|Java Development Kit]] (JDK) 1.5.0.<ref name="jdk5release">
In [[Java (programming language)|Java]], a foreach-construct was introduced in [[Software:Java Development Kit|Java Development Kit]] (JDK) 1.5.0.<ref name="jdk5release">
"Enhanced for Loop - This new language construct[...]"
"Enhanced for Loop - This new language construct[...]"
Line 544: Line 531:
}}</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}}
}}</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}}


<source lang="Java">
<syntaxhighlight lang="Java">
for (Type item : iterableCollection) {
for (Type item : iterableCollection) {
     // Do something to item
     // Do something to item
}
}
</source>
</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}}
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}}
<source lang="Java">
<syntaxhighlight lang="Java">
   List<Integer> intList = List.of(1, 2, 3, 4);
   List<Integer> intList = List.of(1, 2, 3, 4);
   intList.stream().forEach(i -> System.out.println(i));
   intList.stream().forEach(i -> System.out.println(i));
</source>
</syntaxhighlight>


=== JavaScript ===
=== JavaScript ===
The ECMAScript 6 standard has <code>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of for..of]</code> for index-less iteration over generators, arrays and more:
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">
<source lang="JavaScript">
myArray.forEach(function (item, index) {
for (var item of array){
    // Do stuff with item and index
     // Do stuff
    // 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
}
}
</source>
</syntaxhighlight>


Alternatively, function-based style: <ref>{{Cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach|title=Array.prototype.forEach() - JavaScript &#124; MDN|date=16 December 2023 }}</ref>
For unordered iteration over the keys in an object, [[JavaScript]] features the <code>for..in</code> loop:


<source lang="JavaScript">
<syntaxhighlight lang="javascript">
array.forEach(item => {
for (const key in myObject) {
    // Do stuff
     // Do stuff with myObject[key]
})
</source>
 
For unordered iteration over the keys in an Object, [[JavaScript]] features the <code>for...in</code> loop:
 
<source lang="JavaScript">
for (var key in object) {
     // Do stuff with object[key]
}
}
</source>
</syntaxhighlight>


To limit the iteration to the object's own properties, excluding those 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").
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>


<source lang="JavaScript">
<syntaxhighlight lang="javascript">for (const key in myObject) {
for (var key in object) {
    // Available in older browsers
     if (object.hasOwnProperty(key)) {
     if (myObject.hasOwnProperty(key)) {
         // Do stuff with object[key]
         // Do stuff with object[key]
     }
     }
}
    // Preferred in modern browsers
</source>
    if (Object.hasOwn(myObject, key)) {
        // Do stuff with object[key]
    }
}</syntaxhighlight>


ECMAScript 5 provided Object.keys method, to transfer the own keys of an object into array.<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>
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>
<source lang="JavaScript">
<syntaxhighlight lang="javascript">
var book = { name: "A Christmas Carol", author: "Charles Dickens" };  
const book = {  
for(var key of Object.keys(book)){
    name: "A Christmas Carol",  
     alert("PropertyName = " key + " Property Value = " + book[key]);
    author: "Charles Dickens"  
};  
for (const key of Object.keys(book)) {
     console.log(`Key: ${key}, Value: ${book[key]}`);
}
}
</source>
</syntaxhighlight>


=== Lua ===
=== Lua ===
{{Main|Lua (programming language)}}
{{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>
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:<source lang="lua">
Iterate only through numerical index values:<syntaxhighlight lang="lua">
for index, value in ipairs(array) do
for index, value in ipairs(array) do
-- do something
-- do something
end
end
</source>Iterate through all index values:<source lang="lua">
</syntaxhighlight>Iterate through all index values:<syntaxhighlight lang="lua">
for index, value in pairs(array) do
for index, value in pairs(array) do
-- do something
-- do something
end
end
</source>
</syntaxhighlight>


=== Mathematica ===
=== Mathematica ===
In [[Software:Mathematica|Mathematica]], <code>Do</code> will simply evaluate an expression for each element of a list, without returning any value.
In [[Software:Mathematica|Mathematica]], <code>Do</code> will simply evaluate an expression for each element of a list, without returning any value.


<source lang="Mathematica">
<syntaxhighlight lang="Mathematica">
In[]:= Do[doSomethingWithItem, {item, list}]
In[]:= Do[doSomethingWithItem, {item, list}]
</source>
</syntaxhighlight>


It is more common to use <code>Table</code>, which returns the result of each evaluation in a new list.
It is more common to use <code>Table</code>, which returns the result of each evaluation in a new list.


<source lang="Mathematica">
<syntaxhighlight lang="Mathematica">
In[]:= list = {3, 4, 5};
In[]:= list = {3, 4, 5};


In[]:= Table[item^2, {item, list}]
In[]:= Table[item^2, {item, list}]
Out[]= {9, 16, 25}
Out[]= {9, 16, 25}
</source>
</syntaxhighlight>


=== MATLAB ===
=== MATLAB ===
{{Main|Software:MATLAB}}
{{Main|Software:MATLAB}}
 
<syntaxhighlight lang="MATLAB">
<source lang="MATLAB">
for item = array
for item = array
%do something
%do something
end
end
</source>
</syntaxhighlight>


=== Mint ===
=== Mint ===
For each loops are supported in Mint, possessing the following syntax:
For each loops are supported in Mint, possessing the following syntax:
<source lang="Ruby">
<syntaxhighlight lang="Ruby">
for each element of list
for each element of list
     /* 'Do something.' */
     /* 'Do something.' */
end
end
</source>
</syntaxhighlight>


The <code>for (;;)</code> or <code>while (true)</code> [[Infinite loop|infinite loop]]
The <code>for (;;)</code> or <code>while (true)</code> [[Infinite loop|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>
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>


<source lang="Ruby">
<syntaxhighlight lang="Ruby">
import type
import type
/* 'This function is mapped to'
/* 'This function is mapped to'
Line 667: Line 653:
     /* 'Do something forever.' */
     /* 'Do something forever.' */
end
end
</source>
</syntaxhighlight>


=== Objective-C ===
=== 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.
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.


<source lang="ObjC">
<syntaxhighlight lang="ObjC">
NSArray *a = [NSArray new];      // Any container class can be substituted
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
for(id obj in a) {                // Dynamic typing is used. The type of object stored
                                   // Type of object stored in 'a'. In fact, there can be
                                   // in 'a' can be unknown. The array can hold many different
                                   // many different types of object in the array.
                                   // types of object.


     printf("%s\n", [[obj description] UTF8String]);  // Must use UTF8String with %s
     printf("%s\n", [[obj description] UTF8String]);  // Must use UTF8String with %s
     NSLog(@"%@", obj);                              // Leave as an object
     NSLog(@"%@", obj);                              // Leave as an object
}
}
</source>
</syntaxhighlight>


NSArrays can also broadcast a message to their members:
NSArrays can also broadcast a message to their members:


<source lang="ObjC">
<syntaxhighlight lang="ObjC">
NSArray *a = [NSArray new];
NSArray *a = [NSArray new];


[a makeObjectsPerformSelector:@selector(printDescription)];
[a makeObjectsPerformSelector:@selector(printDescription)];
</source>
</syntaxhighlight>


Where [[Blocks (C language extension)|blocks]] are available, an NSArray can automatically perform a block on every contained item:
Where [[Blocks (C language extension)|blocks]] are available, an NSArray can automatically perform a block on every contained item:


<source lang="ObjC">
<syntaxhighlight lang="ObjC">
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
{
Line 702: Line 687:
*stop = YES;
*stop = YES;
}];
}];
</source>
</syntaxhighlight>


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


<source lang="ObjC">
<syntaxhighlight lang="ObjC">
NSDictionary *d = [NSDictionary new];
NSDictionary *d = [NSDictionary new];


Line 714: Line 699:
     NSLog(@"%@", obj);
     NSLog(@"%@", obj);
}
}
</source>
</syntaxhighlight>


=== OCaml ===
=== OCaml ===
 
[[OCaml]] is a [[Functional programming|functional programming]] language. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.
[[OCaml]] is a functional language. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.


For lists:
For lists:


<source lang="OCaml">
<syntaxhighlight lang="OCaml">
List.iter (fun x -> print_int x) [1;2;3;4];;  
List.iter (fun x -> print_int x) [1;2;3;4];;  
</source>
</syntaxhighlight>


or in short way:
or in short way:


<source lang="OCaml">
<syntaxhighlight lang="OCaml">
List.iter print_int [1;2;3;4];;  
List.iter print_int [1;2;3;4];;  
</source>
</syntaxhighlight>


For arrays:
For arrays:


<source lang="OCaml">
<syntaxhighlight lang="OCaml">
Array.iter (fun x -> print_int x) [|1;2;3;4|];;
Array.iter (fun x -> print_int x) [|1;2;3;4|];;
</source>
</syntaxhighlight>


or in short way:
or in short way:


<source lang="OCaml">
<syntaxhighlight lang="OCaml">
Array.iter print_int [|1;2;3;4|];;
Array.iter print_int [|1;2;3;4|];;
</source>
</syntaxhighlight>


=== ParaSail ===
=== ParaSail ===
The [[ParaSail (programming language)|ParaSail]] parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:
The [[ParaSail (programming language)|ParaSail]] parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:


<source lang="parasail">
<syntaxhighlight lang="parasail">
var Con : Container<Element_Type> := ...
var Con : Container<Element_Type> := ...
// ...
// ...
Line 754: Line 737:
   // ... do something with Elem
   // ... do something with Elem
end loop
end loop
</source>
</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":
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":
<source lang="parasail">
<syntaxhighlight lang="parasail">
var My_Map : Map<Key_Type => Univ_String, Value_Type => Tree<Integer>> := ...
var My_Map : Map<Key_Type => Univ_String, Value_Type => Tree<Integer>> := ...
const My_Set : Set<Univ_String> := ["abc", "def", "ghi"];
const My_Set : Set<Univ_String> := ["abc", "def", "ghi"];
Line 764: Line 747:
   // ... do something with Str or Tr
   // ... do something with Str or Tr
end loop
end loop
</source>
</syntaxhighlight>


=== Pascal ===
=== Pascal ===
In [[Pascal (programming language)|Pascal]], ISO standard 10206:1990 introduced iteration over [[Pascal (programming language)#Set types|set types]], thus:
In [[Pascal (programming language)|Pascal]], ISO standard 10206:1990 introduced iteration over [[Pascal (programming language)#Set types|set types]], thus:


<source lang="Pascal">
<syntaxhighlight lang="Pascal">
var
var
   elt: ElementType;
   elt: ElementType;
Line 779: Line 761:
for elt in eltset do
for elt in eltset do
   { ... do something with elt }
   { ... do something with elt }
</source>
</syntaxhighlight>


=== Perl ===
=== 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.
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:
List literal example:


<source lang="Perl">
<syntaxhighlight lang="Perl">
foreach (1, 2, 3, 4) {
foreach (1, 2, 3, 4) {
     print $_;
     print $_;
}
}
</source>
</syntaxhighlight>


Array examples:
Array examples:


<source lang="Perl">
<syntaxhighlight lang="Perl">
foreach (@arr) {
foreach (@arr) {
     print $_;
     print $_;
}
}
</source>
</syntaxhighlight>


<source lang="Perl">
<syntaxhighlight lang="Perl">
foreach $x (@arr) { #$x is the element in @arr
foreach $x (@arr) { #$x is the element in @arr
     print $x;
     print $x;
}  
}  
</source>
</syntaxhighlight>


Hash example:
Hash example:


<source lang="Perl">
<syntaxhighlight lang="Perl">
foreach $x (keys %hash) {
foreach $x (keys %hash) {
     print $x . " = " . $hash{$x}; # $x is a key in %hash and $hash{$x} is its value
     print $x . " = " . $hash{$x}; # $x is a key in %hash and $hash{$x} is its value
}
}
</source>
</syntaxhighlight>


Direct modification of collection members:
Direct modification of collection members:


<source lang="Perl">
<syntaxhighlight lang="Perl">
@arr = ( 'remove-foo', 'remove-bar' );
@arr = ( 'remove-foo', 'remove-bar' );
foreach $x (@arr){
foreach $x (@arr){
Line 823: Line 804:
}
}
# Now @arr = ('foo', 'bar');
# Now @arr = ('foo', 'bar');
</source>
</syntaxhighlight>


=== PHP ===
=== PHP ===
{{Main|PHP syntax and semantics}}
{{Main|PHP syntax and semantics}}
 
<syntaxhighlight lang="php">
<source lang="php">
foreach ($set as $value) {
foreach ($set as $value) {
     // Do something to $value;
     // Do something to $value;
}
}
</source>
</syntaxhighlight>


It is also possible to extract both keys and values using the alternate syntax:
It is also possible to extract both keys and values using the alternate syntax:


<source lang="php">
<syntaxhighlight lang="php">
foreach ($set as $key => $value) {
foreach ($set as $key => $value) {
     echo "{$key} has a value of {$value}";
     echo "{$key} has a value of {$value}";
}
}
</source>
</syntaxhighlight>


Direct modification of collection members:
Direct modification of collection members:


<source lang="php">
<syntaxhighlight lang="php">
$arr = array(1, 2, 3);
$arr = array(1, 2, 3);
foreach ($arr as &$value) { // Note the &, $value is a reference to the original value inside $arr
foreach ($arr as &$value) { // The &, $value is a reference to the original value inside $arr
     $value++;
     $value++;
}
}
Line 855: Line 835:
     $value++;
     $value++;
}
}
</source>
</syntaxhighlight>
* [https://php.net/foreach More information]
* [https://php.net/foreach More information]


=== Python ===
=== Python ===
{{Main|Python (programming language)}}
{{Main|Python (programming language)}}
 
<syntaxhighlight lang="python">
<source lang="python">
for item in iterable_collection:
for item in iterable_collection:
     # Do something with item
     # Do something with item
</source>
</syntaxhighlight>


Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in [[Associative array|associative array]]s:
Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in [[Associative array|dictionaries]]:


<source lang="python">
<syntaxhighlight lang="python">
for key, value in some_dict.items():  # Direct iteration on a dict iterates on its keys
for key, value in some_dict.items():  # Direct iteration on a dict iterates on its keys
     # Do stuff
     # Do stuff
</source>
</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...
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...


<source lang="python">
<syntaxhighlight lang="python">
for i in range(len(seq)):
for i in range(len(seq)):
     # Do something to seq[i]
     # Do something to seq[i]
</source>
</syntaxhighlight>


... though using the <code>enumerate</code> function is considered more "Pythonic":
... although using the <code>enumerate</code> function is considered more "Pythonic":


<source lang="python">
<syntaxhighlight lang="python">
for i, item in enumerate(seq):
for i, item in enumerate(seq):
     # Do stuff with item
     # Do stuff with item
     # Possibly assign it back to seq[i]
     # Possibly assign it back to seq[i]
</source>
</syntaxhighlight>


=== R ===
=== R ===
{{Main|R (programming language)}}
{{Main|R (programming language)}}
 
<syntaxhighlight lang="R">
<source lang="R">
for (item in object) {
for (item in object) {
     # Do something with item
     # Do something with item
}
}
</source>
</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...
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...


<source lang="R">
<syntaxhighlight lang="R">
for (i in seq_along(object)) {
for (i in seq_along(object)) {
     # Do something with objecti
     # Do something with objecti
}
}
</source>
</syntaxhighlight>


=== Racket ===
=== Racket ===
{{Main|Racket (programming language)}}
{{Main|Racket (programming language)}}
<source lang="racket">
<syntaxhighlight lang="racket">
(for ([item set])
(for ([item set])
   (do-something-with item))
   (do-something-with item))
</source>
</syntaxhighlight>


or using the conventional Scheme <code>for-each</code> function:
or using the conventional Scheme <code>for-each</code> function:


<source lang="racket">
<syntaxhighlight lang="racket">
(for-each do-something-with a-list)
(for-each do-something-with a-list)
</source>
</syntaxhighlight>
<code>do-something-with</code> is a one-argument function.
<code>do-something-with</code> is a one-argument function.


=== Raku ===
=== 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).
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:
List literal example:


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
for 1..4 {
for 1..4 {
     .say;
     .say;
}
}
</source>
</syntaxhighlight>


Array examples:
Array examples:


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
for @arr {
for @arr {
     .say;
     .say;
}
}
</source>
</syntaxhighlight>


The for loop in its statement modifier form:
The for loop in its statement modifier form:


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
.say for @arr;
.say for @arr;
</source>
</syntaxhighlight>


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
for @arr -> $x {
for @arr -> $x {
     say $x;
     say $x;
}  
}  
</source>
</syntaxhighlight>


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
for @arr -> $x, $y {    # more than one item at a time
for @arr -> $x, $y {    # more than one item at a time
     say "$x, $y";
     say "$x, $y";
}  
}  
</source>
</syntaxhighlight>


Hash example:
Hash example:


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
for keys %hash -> $key {
for keys %hash -> $key {
     say "$key: $hash{$key}";
     say "$key: $hash{$key}";
}
}
</source>
</syntaxhighlight>


or
or


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
for %hash.kv -> $key, $value {
for %hash.kv -> $key, $value {
     say "$key: $value";
     say "$key: $value";
}
}
</source>
</syntaxhighlight>


or
or


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
for %hash -> $x {
for %hash -> $x {
     say "$x.key(): $x.value()";    # Parentheses needed to inline in double quoted string
     say "$x.key(): $x.value()";    # Parentheses needed to inline in double quoted string
}
}
</source>
</syntaxhighlight>




Direct modification of collection members with a doubly pointy block, ''<->'':  
Direct modification of collection members with a doubly pointy block, ''<->'':  


<source lang="Perl6">
<syntaxhighlight lang="Perl6">
my @arr = 1,2,3;
my @arr = 1,2,3;
for @arr <-> $x {
for @arr <-> $x {
Line 990: Line 967:
}
}
# Now @arr = 2,4,6;
# Now @arr = 2,4,6;
</source>
</syntaxhighlight>


=== Ruby ===
=== Ruby ===
{{Main|Ruby (programming language)}}
{{Main|Ruby (programming language)}}
 
<syntaxhighlight lang="Ruby">
<source lang="Ruby">
set.each do |item|
set.each do |item|
   # do something to item
   # do something to item
end
end
</source>
</syntaxhighlight>


or
or


<source lang="Ruby">
<syntaxhighlight lang="Ruby">
for item in set
for item in set
   # do something to item
   # do something to item
end
end
</source>
</syntaxhighlight>


This can also be used with a hash.
This can also be used with a hash.


<source lang="Ruby">
<syntaxhighlight lang="Ruby">
set.each do |key,value|
set.each do |key,value|
   # do something to key
   # do something to key
   # do something to value
   # do something to value
end
end
</source>
</syntaxhighlight>


=== Rust ===
=== Rust ===
{{Main|Rust (programming language)}}
{{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.


The <code>for</code> loop has the structure <source lang="rust" inline>for <pattern> in <expression> { /* optional statements */ }</source>. 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">
 
<source lang="Rust">
let mut numbers = vec![1, 2, 3];
let mut numbers = vec![1, 2, 3];


Line 1,050: Line 1,025:
// Errors with "borrow of moved value":
// Errors with "borrow of moved value":
// println!("{:?}", numbers);
// println!("{:?}", numbers);
</source>
</syntaxhighlight>


=== Scala ===
=== Scala ===
{{Main|Scala (programming language)}}
{{Main|Scala (programming language)}}
 
<syntaxhighlight lang="Scala">
<source lang="Scala">
// return list of modified elements
// return list of modified elements
items map { x => doSomething(x) }
items map { x => doSomething(x) }
Line 1,072: Line 1,046:
// pattern matching example in for-comprehension
// pattern matching example in for-comprehension
for ((key, value) <- someMap) println(s"$key -> $value")
for ((key, value) <- someMap) println(s"$key -> $value")
</source>
</syntaxhighlight>


=== Scheme ===
=== Scheme ===
{{Main|Scheme (programming language)}}
{{Main|Scheme (programming language)}}
<source lang="Scheme">
<syntaxhighlight lang="Scheme">
(for-each do-something-with a-list)
(for-each do-something-with a-list)
</source>
</syntaxhighlight>
<code>do-something-with</code> is a one-argument function.
<code>do-something-with</code> is a one-argument function.


=== Smalltalk ===
=== Smalltalk ===
{{Main|Smalltalk}}
{{Main|Smalltalk}}
<source lang="Smalltalk">
<syntaxhighlight lang="Smalltalk">
collection do: [:item| "do something to item" ]
collection do: [:item| "do something to item" ]
</source>
</syntaxhighlight>


=== Swift ===
=== 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>
[[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>


<source lang="objc">
<syntaxhighlight lang="objc">
for thing in someCollection {
for thing in someCollection {
     // do something with thing
     // do something with thing
}
}
</source>
</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.
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.


<source lang="objc">
<syntaxhighlight lang="objc">
for i in 0..<10 {
for i in 0..<10 {
     // 0..<10 constructs a half-open range, so the loop body
     // 0..<10 constructs a half-open range, so the loop body
Line 1,109: Line 1,082:
     // is repeated for i = 0, i = 1, …, i = 9, i = 10.
     // is repeated for i = 0, i = 1, …, i = 9, i = 10.
}
}
</source>
</syntaxhighlight>


=== SystemVerilog ===
=== SystemVerilog ===
[[SystemVerilog]] supports iteration over any vector or array type of any dimensionality using the <code>foreach</code> keyword.
[[SystemVerilog]] supports iteration over any vector or array type of any dimensionality using the <code>foreach</code> keyword.


Line 1,121: Line 1,093:
|-
|-
|
|
<source lang="systemverilog">
<syntaxhighlight lang="systemverilog">
int  array_1d[] = '{ 3, 2, 1, 0 };
int  array_1d[] = '{ 3, 2, 1, 0 };


foreach array_1d[index]
foreach array_1d[index]
   $display("array_1d[%0d]: %0d", index, array_1d[index]);
   $display("array_1d[%0d]: %0d", index, array_1d[index]);
</source>
</syntaxhighlight>
|
|
  array_1d[0]: 3
  array_1d[0]: 3
Line 1,140: Line 1,112:
|-
|-
|
|
<source lang="systemverilog">
<syntaxhighlight lang="systemverilog">
int  array_2d[string][] = '{ "tens": '{ 10, 11 },
int  array_2d[string][] = '{ "tens": '{ 10, 11 },
                             "twenties": '{ 20, 21 } };
                             "twenties": '{ 20, 21 } };
Line 1,146: Line 1,118:
foreach array_2d[key,index]
foreach array_2d[key,index]
   $display("array_2d[%s,%0d]: %0d", key, index, array_2d[key,index]);
   $display("array_2d[%s,%0d]: %0d", key, index, array_2d[key,index]);
</source>
</syntaxhighlight>
|
|
  array_2d[tens,0]: 10
  array_2d[tens,0]: 10
Line 1,155: Line 1,127:


=== Tcl ===
=== 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.  
[[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"
{| class="wikitable"
Line 1,161: Line 1,132:
|-
|-
|
|
<source lang=Tcl>
<syntaxhighlight lang=Tcl>
foreach {i j} {1 2 3 4 5 6} {
foreach {i j} {1 2 3 4 5 6} {
     puts "$i $j"
     puts "$i $j"
}
}
</source>
</syntaxhighlight>
|
|
  1 2
  1 2
Line 1,177: Line 1,148:
|-
|-
|
|
<source lang=Tcl>
<syntaxhighlight lang=Tcl>
foreach i {1 2 3} j {a b c}  {
foreach i {1 2 3} j {a b c}  {
     puts "$i $j"
     puts "$i $j"
}
}
</source>
</syntaxhighlight>
|
|
  1 a
  1 a
Line 1,188: Line 1,159:
|}
|}


=== Visual Basic .NET ===
=== Visual Basic (.NET) ===
{{Main|Visual Basic .NET}}
{{Main|Visual Basic (.NET)}}
<source lang="VBNet">
<syntaxhighlight lang="VBNet">
For Each item In enumerable
For Each item In enumerable
     ' Do something with item.
     ' Do something with item.
Next
Next
</source>
</syntaxhighlight>


or without [[Type inference|type inference]]
or without [[Type inference|type inference]]


<source lang="VBNet">
<syntaxhighlight lang="VBNet">
For Each item As type In enumerable
For Each item As type In enumerable
     ' Do something with item.
     ' Do something with item.
Next
Next
</source>
</syntaxhighlight>


=== Windows ===
=== Windows ===
==== Conventional command processor ====
==== Conventional command processor ====
{{main|Software:COMMAND.COM|Software:Cmd.exe}}
{{main|Software:COMMAND.COM|cmd.exe}}
Invoke a hypothetical <code>frob</code> command three times, giving it a color name each time.
Invoke a hypothetical <code>frob</code> command three times, giving it a color name each time.
<source lang="doscon">
<syntaxhighlight lang="doscon">
C:\>FOR %%a IN ( red green blue ) DO frob %%a
C:\>FOR %%a IN ( red green blue ) DO frob %%a
</source>
</syntaxhighlight>


==== Windows PowerShell ====
==== Windows PowerShell ====
<source lang="PowerShell">
<syntaxhighlight lang="PowerShell">
foreach ($item in $set) {
foreach ($item in $set) {
     # Do something to $item
     # Do something to $item
}
}
</source>
</syntaxhighlight>


From a pipeline
From a pipeline


<source lang="PowerShell">
<syntaxhighlight lang="PowerShell">
$list | ForEach-Object {Write-Host $_}
$list | ForEach-Object {Write-Host $_}


Line 1,227: Line 1,198:
$list | foreach {write $_}
$list | foreach {write $_}
$list | % {write $_}
$list | % {write $_}
</source>
</syntaxhighlight>


=== XSLT ===
=== XSLT ===
{{Main|XSLT}}
{{Main|XSLT}}
<source lang="xml">
<syntaxhighlight lang="xml">
  <xsl:for-each select="set">
  <xsl:for-each select="set">
   <!-- do something for the elements in <set> -->
   <!-- do something for the elements in <set> -->
  </xsl:for-each>
  </xsl:for-each>
</source><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>
</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 ==
== See also ==
Line 1,247: Line 1,218:


[[Category:Control flow]]
[[Category:Control flow]]
[[Category:Iteration in programming]]
[[Category:Programming language comparisons]]
[[Category:Programming language comparisons]]
<!-- Hidden categories below -->
[[Category:Articles with example C code]]
[[Category:Articles with example C Sharp code]]
[[Category:Articles with example OCaml code]]


ru:Цикл просмотра
ru:Цикл просмотра
{{Sourceattribution|Foreach loop}}
{{Sourceattribution|Foreach loop}}

Latest revision as of 20:16, 17 June 2025

Short description: Control flow statement for traversing items in a collection
foreach loops are almost always used to iterate over items in a sequence of elements.

In computer programming, foreach loop (or for-each loop) is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops[1] 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

Syntax varies among languages. Most use the simple word for, although other use the more logical word foreach, roughly as follows:

foreach(key, value) in collection {
  # Do something to value #
}

Language support

Programming languages which support foreach loops include ABC, ActionScript, Ada, C++ (since C++11), C#, ColdFusion Markup Language (CFML), Cobra, D, Daplex (query language), Delphi, ECMAScript, Erlang, Java (since 1.5), JavaScript, Lua, Objective-C (since 2.0), ParaSail, Perl, PHP, Prolog,[2] Python, R, REALbasic, Rebol,[3] Red,[4] 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.

ActionScript 3.0

ActionScript supports the ECMAScript 4.0 Standard[5] for for each .. in[6] which pulls the value at each index.

var foo:Object = {
	"apple":1,
	"orange":2
};

for each (var value:int in foo) { 
	trace(value); 
}

// returns "1" then "2"

It also supports for .. in[7] which pulls the key at each index.

for (var key:String in foo) { 
	trace(key); 
}

// returns "apple" then "orange"

Ada

Ada supports foreach loops as part of the normal for loop. Say X is an array:

for I in X'Range loop
   X (I) := Get_Next_Element;
end loop;

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...):

for Obj of X loop
   -- Work on Obj
end loop;

C

The 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 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

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

C int array as a collection of int (array size known at compile-time)

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

Most general: string or array as collection (collection size known at run-time)

idxtype can be removed and typeof(col[0]) used in its place with GCC
#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;
}

C#

In C#, assuming that myArray is an array of integers:

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

Language Integrated Query (LINQ) provides the following syntax, accepting a delegate or lambda expression:

myArray.ToList().ForEach(x => Console.WriteLine(x));

C++

C++11 provides a foreach loop. The syntax is similar to that of Java:

#include <iostream>

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

  for (int i : myint)
  {
    std::cout << i << '\n';
  }
}

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 [8])

The range-based for is syntactic sugar equivalent to:

for (auto __anon = begin(myint); __anon != end(myint); ++__anon)
  {
    auto i = *__anon;
    std::cout << i << '\n';
  }

The compiler uses argument-dependent lookup to resolve the begin and end functions.[9]

The C++ Standard Library also supports for_each,[10] 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.

#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';
  });
}

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

#include <QList>
#include <QDebug>

int main()
{
  QList<int> list;

  list << 1 << 2 << 3 << 4 << 5;

  foreach (int i, list)
  {
    qDebug() << i;
  }
}

Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:[12]

#include <boost/foreach.hpp>
#include <iostream>
 
int main()
{
  int myint[] = {1, 2, 3, 4, 5};
 
  BOOST_FOREACH(int &i, myint)
  {
    std::cout << i << '\n';
  }
}

C++/CLI

The C++/CLI language proposes a construct similar to C#.

Assuming that myArray is an array of integers:

for each (int x in myArray)
{
    Console::WriteLine(x);
}

ColdFusion Markup Language (CFML)

Main page: ColdFusion Markup Language

Script syntax

// 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#;");
});

Tag syntax

<!--- arrays --->
<cfloop index="v" array="#['a','b','c','d','e']#">
  <cfoutput>#v#</cfoutput><!--- a b c d e  --->
</cfloop>

CFML incorrectly identifies the value as "index" in this construct; the index variable does receive the actual value of the array element, not its index.

<!--- structs --->
<cfloop item="k" collection="#collection#">
    <cfoutput>#collection[k]#</cfoutput>
</cfloop>

Common Lisp

Common Lisp provides foreach ability either with the dolist macro:

(dolist (i '(1 3 5 6 8 10 14 17))
  (print i))

or the powerful loop macro to iterate on more data types

(loop for i in '(1 3 5 6 8 10 14 17)
      do (print i))

and even with the mapcar function:

(mapcar #'print '(1 3 5 6 8 10 14 17))

D

Main page: D (programming language)
foreach(item; set) {
  // do something to item
}

or

foreach(argument) {
  // pass value
}

Dart

Main page: Dart (programming language)
for (final element in someCollection) {
  // do something with element
}

Object Pascal, Delphi

Main pages: Object Pascal and Delphi (software)

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

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) or some (effecting existential quantification).

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'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):

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

Using the one-value form gets the index/key (first element):

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

[13]

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 allows looping over lists with monadic actions using mapM_ and forM_ (mapM_ with its arguments flipped) from Control.Monad:

code prints
mapM_ print [1..4]
1
2
3
4
forM_ "test" $ \char -> do 
    putChar char
    putChar char
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 traverse (for with its arguments flipped) and mapM (forM with its arguments flipped) from Data.Traversable.

Haxe

Main page: Haxe
for (value in iterable) {
    trace(value);
}

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

Java

In Java, a foreach-construct was introduced in Java Development Kit (JDK) 1.5.0.[14]

Official sources use several names for the construct. It is referred to as the "Enhanced for Loop",[14] the "For-Each Loop",[15] and the "foreach statement".[16][17]:264

for (Type item : iterableCollection) {
    // Do something to item
}

Java also provides the stream api since java 8:[17]:294-203

List<Integer> intList = List.of(1, 2, 3, 4);
   intList.stream().forEach(i -> System.out.println(i));

JavaScript

In ECMAScript 5, a callback-based forEach() method was added to the array prototype:[18]

myArray.forEach(function (item, index) {
    // Do stuff with item and index 
    // The index variable can be omitted from the parameter list if not needed
});

The ECMAScript 6 standard introduced a more conventional for..of syntax that works on all iterables rather than operating on only array instances. However, no index variable is available with the syntax.

for (const item of myArray) {
    // Do stuff with item
}

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

for (const key in myObject) {
    // Do stuff with myObject[key]
}

To limit the iteration to the object's own properties, excluding those inherited through the prototype chain, it's often useful to add a hasOwnProperty() test (or a hasOwn() test if supported).[19]

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]
    }
}

Alternatively, the Object.keys() method combined with the for..of loop can be used for a less verbose way to iterate over the keys of an object.[20]

const book = { 
    name: "A Christmas Carol", 
    author: "Charles Dickens" 
}; 
for (const key of Object.keys(book)) {
    console.log(`Key: ${key}, Value: ${book[key]}`);
}

Lua

Main page: Lua (programming language)

Source:[21]

Iterate only through numerical index values:

for index, value in ipairs(array) do
	-- do something
end

Iterate through all index values:

for index, value in pairs(array) do

-- do something

end

Mathematica

In Mathematica, Do will simply evaluate an expression for each element of a list, without returning any value.

In[]:= Do[doSomethingWithItem, {item, list}]

It is more common to use Table, which returns the result of each evaluation in a new list.

In[]:= list = {3, 4, 5};

In[]:= Table[item^2, {item, list}]
Out[]= {9, 16, 25}

MATLAB

Main page: Software:MATLAB
for item = array
%do something
end

Mint

For each loops are supported in Mint, possessing the following syntax:

for each element of list
    /* 'Do something.' */
end

The for (;;) or while (true) infinite loop in Mint can be written using a for each loop and an infinitely long list.[22]

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

Objective-C

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) {                // 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
}

NSArrays can also broadcast a message to their members:

NSArray *a = [NSArray new];

[a makeObjectsPerformSelector:@selector(printDescription)];

Where blocks 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 nonunique) object.
    NSLog(@"%@", obj);
}

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:

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

ParaSail

The ParaSail parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:

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

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":

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

Pascal

In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus:

var
  elt: ElementType;
  eltset: set of ElementType;

{...}

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

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:

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-//;
}
# Now @arr = ('foo', 'bar');

PHP

Main page: PHP syntax and semantics
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 ($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++;
}

Python

Main page: Python (programming language)
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 dictionaries:

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]

... although 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]

R

Main page: R (programming language)
for (item in object) {
    # Do something with item
}

As for ... in is the only kind of for loop in R, the equivalent to the "counter" loop found in other languages is...

for (i in seq_along(object)) {
    # Do something with objecti
}

Racket

Main page: Racket (programming language)
(for ([item set])
  (do-something-with item))

or using the conventional Scheme for-each function:

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

do-something-with is a one-argument function.

Raku

In 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:

for 1..4 {
    .say;
}

Array examples:

for @arr {
    .say;
}

The for loop in its statement modifier form:

.say for @arr;
for @arr -> $x {
    say $x;
}
for @arr -> $x, $y {    # more than one item at a time
    say "$x, $y";
}

Hash example:

for keys %hash -> $key {
    say "$key: $hash{$key}";
}

or

for %hash.kv -> $key, $value {
    say "$key: $value";
}

or

for %hash -> $x {
    say "$x.key(): $x.value()";    # Parentheses needed to inline in double quoted string
}


Direct modification of collection members with a doubly pointy block, <->:

my @arr = 1,2,3;
for @arr <-> $x {
    $x *= 2;
}
# Now @arr = 2,4,6;

Ruby

Main page: Ruby (programming language)
set.each do |item|
  # do something to item
end

or

for item in set
  # do something to item
end

This can also be used with a hash.

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

Rust

Main page: Rust (programming language)

The for loop has the structure for <pattern> in <expression> { /* optional statements */ }. It implicitly calls the IntoIterator::into_iter method on the expression, and uses the resulting value, which must implement the Iterator trait. If the expression is itself an iterator, it is used directly by the for loop through an implementation of IntoIterator for all Iterators that returns the iterator unchanged. The loop calls the Iterator::next method on the iterator before executing the loop body. If Iterator::next returns Some( ), the value inside is assigned to the pattern and the loop body is executed; if it returns None, the loop is terminated.

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

Scala

Main page: Scala (programming language)
// 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")

Scheme

Main page: Scheme (programming language)
(for-each do-something-with a-list)

do-something-with is a one-argument function.

Smalltalk

Main page: Smalltalk
collection do: [:item| "do something to item" ]

Swift

Swift uses the forin construct to iterate over members of a collection.[23]

for thing in someCollection {
    // do something with thing
}

The forin loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times.

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

SystemVerilog

SystemVerilog supports iteration over any vector or array type of any dimensionality using the foreach keyword.

A trivial example iterates over an array of integers:

code prints
int  array_1d[] = '{ 3, 2, 1, 0 };

foreach array_1d[index]
  $display("array_1d[%0d]: %0d", index, array_1d[index]);
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:

code prints
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]);
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.

code prints
foreach {i j} {1 2 3 4 5 6} {
    puts "$i $j"
}
1 2
3 4
5 6

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:

code prints
foreach i {1 2 3} j {a b c}  {
    puts "$i $j"
}
1 a
2 b
3 c

Visual Basic (.NET)

Main page: Visual Basic (.NET)
For Each item In enumerable
    ' Do something with item.
Next

or without type inference

For Each item As type In enumerable
    ' Do something with item.
Next

Windows

Conventional command processor

Main pages: Software:COMMAND.COM and cmd.exe

Invoke a hypothetical frob command three times, giving it a color name each time.

C:\>FOR %%a IN ( red green blue ) DO frob %%a

Windows PowerShell

foreach ($item in $set) {
    # Do something to $item
}

From a pipeline

$list | ForEach-Object {Write-Host $_}

# or using the aliases
$list | foreach {write $_}
$list | % {write $_}

XSLT

Main page: XSLT
<xsl:for-each select="set">
   <!-- do something for the elements in <set> -->
 </xsl:for-each>

[24]

See also

References

  1. "D Programming Language foreach Statement Documentation". Digital Mars. http://www.digitalmars.com/d/statement.html#ForeachStatement. 
  2. "SWI-Prolog – foreach/2". https://www.swi-prolog.org/pldoc/man?predicate=foreach/2. 
  3. "Rebol". http://www.rebol.com/. 
  4. "Red Programming Language". https://www.red-lang.org/. 
  5. "Proposed ECMAScript 4th Edition – Language Overview". https://www.ecma-international.org/activities/Languages/Language%20overview.pdf. 
  6. "for each..in". https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#for_each..in. 
  7. "for..in". https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#for..in. 
  8. "C++11 Features in Visual C++ 11 - Visual C++ Team Blog - Site Home - MSDN Blogs". Blogs.msdn.com. 2011-09-12. http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx. 
  9. "Range-based for loop (since C++11)". en.cppreference.com. https://en.cppreference.com/w/cpp/language/range-for. 
  10. "std::for_each - cppreference". en.cppreference.com. http://en.cppreference.com/w/cpp/algorithm/for_each. 
  11. "Qt 4.2: Generic Containers". Doc.qt.digia.com. http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword. 
  12. Eric Niebler (2013-01-31). "Chapter 9. Boost.Foreach - 1.53.0". Boost.org. http://www.boost.org/doc/libs/1_53_0/doc/html/foreach.html. 
  13. "Range Clause". The Go Programming Language Specification. The Go Programming Language. http://golang.org/ref/spec#RangeClause. 
  14. 14.0 14.1 "Enhanced for Loop - This new language construct[...]" "Java Programming Language, Section: Enhancements in JDK 5". Sun Microsystems, Inc.. 2004. http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html. 
  15. "The For-Each Loop" "The For-Each Loop". Sun Microsystems, Inc.. 2008. http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html. 
  16. "Implementing this interface allows an object to be the target of the "foreach" statement." "Iterable (Java Platform SE 6)". Sun Microsystems, Inc.. 2004. http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html. 
  17. 17.0 17.1 Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991. 
  18. "Array.prototype.forEach() - JavaScript | MDN" (in en-US). 2024-07-25. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach. 
  19. "Object.hasOwn() - JavaScript | MDN" (in en-US). 2023-09-25. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#description. 
  20. "Object.keys". Mozilla Developer Network. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys. 
  21. "Lua Programming/Tables - Wikibooks, open books for an open world" (in en). https://en.wikibooks.org/wiki/Lua_Programming/Tables#Foreach_loop. 
  22. Chu, Oliver. "Mint Tutorial". http://prezi.com/ougvv1wzx2lb/mint-tutorial-part-0/. 
  23. "Control Flow — the Swift Programming Language (Swift 5.5)". https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_153. 
  24. "XSLT <xsl:for-each> Element". W3Schools.com. https://www.w3schools.com/xsl/xsl_for_each.asp. 

ru:Цикл просмотра