
In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, foreach loop (or for-each loop) is a
control flow statement for traversing items in a
collection. is usually used in place of a standard loop
statement. Unlike other loop constructs, however, loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this 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 statement in some languages has some defined order, processing each item in the collection from the first to the last.
The statement in many other languages, especially
array programming
In computer science, array programming refers to solutions that allow the application of operations to an entire set of values at once. Such solutions are commonly used in computational science, scientific and engineering settings.
Modern program ...
languages, does not have any particular order. This simplifies
loop optimization
In compiler theory, loop optimization is the process of increasing execution speed and reducing the overheads associated with loops. It plays an important role in improving cache performance and making effective use of parallel processing capa ...
in general and in particular allows
vector processing
In computing, a vector processor or array processor is a central processing unit (CPU) that implements an instruction set where its Instruction (computer science), instructions are designed to operate efficiently and effectively on large Array d ...
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
Language support
Programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s which support foreach loops include
ABC,
ActionScript
ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (mean ...
,
Ada,
C++ (since
C++11
C++11 is a version of a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior vers ...
),
C#,
ColdFusion Markup Language (CFML),
Cobra,
D,
Daplex (query language),
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), was an ancient sacred precinct and the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient Classical antiquity, classical world. The A ...
,
ECMAScript
ECMAScript (; ES) is a standard for scripting languages, including JavaScript, JScript, and ActionScript. It is best known as a JavaScript standard intended to ensure the interoperability of web pages across different web browsers. It is stan ...
,
Erlang,
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
(since 1.5),
JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
,
Lua,
Objective-C
Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
(since 2.0),
ParaSail,
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
,
PHP,
Prolog
Prolog is a logic programming language that has its origins in artificial intelligence, automated theorem proving, and computational linguistics.
Prolog has its roots in first-order logic, a formal logic. Unlike many other programming language ...
,
Python,
R,
REALbasic,
Rebol,
Red,
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
,
Scala,
Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
,
Swift,
Tcl,
tcsh,
Unix shell
A Unix shell is a Command-line_interface#Command-line_interpreter, command-line interpreter or shell (computing), shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command languag ...
s,
Visual Basic (.NET), and
Windows PowerShell. Notable languages without foreach are
C, and C++ pre-C++11.
ActionScript 3.0
ActionScript
ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (mean ...
supports the ECMAScript 4.0 Standard for
for each .. in
which pulls the value at each index.
var foo:Object = ;
for each (var value:int in foo)
// returns "1" then "2"
It also supports
for .. in
which pulls the key at each index.
for (var key:String in foo)
// returns "apple" then "orange"
Ada
Ada supports foreach loops as part of the normal
for loop
In computer science, a for-loop or for loop is a control flow Statement (computer science), statement for specifying iteration. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfi ...
. 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
/* 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)
C int array as a collection of int (array size known at compile-time)
#include
/* 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 )); ++intpvar)
int main(int argc, char** argv)
Most general: string or array as collection (collection size known at run-time)
: '' can be removed and
typeof(col
used in its place with
GCC''
#include
#include
/* foreach macro viewing an array of given type as a collection of values of given type */
#define arraylen(arr) (sizeof(arr)/sizeof(arr )
#define foreach(idxtype, idxpvar, col, colsiz) \
idxtype* idxpvar; \
for (idxpvar = col; idxpvar < (col + colsiz); ++idxpvar)
int main(int argc, char** argv)
C#
In
C#, assuming that myArray is an array of integers:
foreach (int x in myArray)
Language Integrated Query (LINQ) provides the following syntax, accepting a
delegate or
lambda expression:
myArray.ToList().ForEach(x => Console.WriteLine(x));
C++
C++11
C++11 is a version of a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior vers ...
provides a foreach loop. The syntax is similar to that of
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
:
#include
int main()
C++11 range-based for statements have been implemented in
GNU Compiler Collection
The GNU Compiler Collection (GCC) is a collection of compilers from the GNU Project that support various programming languages, Computer architecture, hardware architectures, and operating systems. The Free Software Foundation (FSF) distributes ...
(GCC) (since version 4.6),
Clang
Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
(since version 3.0) and
Visual C++ 2012 (version 11 )
The range-based
for
is
syntactic sugar equivalent to:
for (auto __anon = begin(myint); __anon != end(myint); ++__anon)
The compiler uses
argument-dependent lookup to resolve the
begin
and
end
functions.
The
C++ Standard Library also supports
for_each
, 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
#include // contains std::for_each
#include
int main()
Qt, a C++ framework, offers a macro providing foreach loops using the STL iterator interface:
#include
#include
int main()
Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:
#include
#include
int main()
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)
ColdFusion Markup Language (CFML)
Script syntax
// arrays
arrayeach( ,2,3,4,5 function(v));
// or
for (v in ,2,3,4,5
// or
// (Railo only; not supported in ColdFusion)
letters = a","b","c","d","e"
letters.each(function(v));
// structs
for (k in collection)
// or
structEach(collection, function(k,v));
// or
// (Railo only; not supported in ColdFusion)
collection.each(function(k,v));
Tag syntax
a','b','c','d','e'">
#v#
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.
#collection
Common Lisp
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
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
foreach(item; set)
or
foreach(argument)
Dart
for (final element in someCollection)
Object Pascal, Delphi
Foreach support was added in
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), was an ancient sacred precinct and the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient Classical antiquity, classical world. The A ...
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
Existentialism is a family of philosophy, philosophical views and inquiry that explore the human individual's struggle to lead an Authenticity (philosophy), authentic life despite the apparent Absurdity#The Absurd, absurdity or incomprehensibili ...
).
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
Using the one-value form gets the index/key (first element):
for index := range someCollection
Groovy
Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1960s and 1970s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The word ...
supports ''for'' loops over collections like arrays, lists and ranges:
def x = ,2,3,4for (v in x) // loop over the 4-element array x
for (v in ,2,3,4 // loop over 4-element literal list
for (v in 1..4) // loop over the range 1..4
Groovy also supports a C-style for loop with an array index:
for (i = 0; i < x.size(); 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 // print every element of the x array
x.each // equivalent to line above, only loop dummy explicitly named "i"
Haskell
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
allows looping over lists with
monadic actions using
mapM_
and
forM_
(
mapM_
with its arguments flipped) fro
Control.Monad
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) fro
Haxe
for (value in iterable)
Lambda.iter(iterable, function(value) trace(value));
Java
In
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, a foreach-construct was introduced in
Java Development Kit (JDK) 1.5.0.
[
"Enhanced for Loop - This new language construct ..
]
Official sources use several names for the construct. It is referred to as the "Enhanced for Loop",
the "For-Each Loop", and the "foreach statement".
for (Type item : iterableCollection)
Java also provides the stream api since java 8:
List 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
A prototype is an early sample, model, or release of a product built to test a concept or process. It is a term used in a variety of contexts, including semantics, design, electronics, and Software prototyping, software programming. A prototype ...
:
myArray.forEach(function (item, index) );
The
ECMAScript 6 standard introduced a more conventional
for..of
/code> 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)
For unordered iteration over the keys in an object, JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
features the for..in
loop:
for (const key in myObject)
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).
for (const key in myObject)
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.
const book = ;
for (const key of Object.keys(book))
Lua
Source:
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, ]
It is more common to use Table
, which returns the result of each evaluation in a new list.
In[]:= list = ;
In[]:= Table[item^2, ]
Out[]=
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.
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'
* ' , 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
Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
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 = SArray new // Any container class can be substituted
for(id obj in a)
NSArrays can also broadcast a message to their members:
NSArray *a = SArray new
makeObjectsPerformSelector:@selector(printDescription)
Where blocks are available, an NSArray can automatically perform a block on every contained item:
yArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
The type of collection being iterated will dictate the item returned with each iteration.
For example:
NSDictionary *d = SDictionary new
for(id key in d)
OCaml
OCaml
OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
is a functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declarat ...
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) ;2;3;4;
or in short way:
List.iter print_int ;2;3;4;
For arrays:
Array.iter (fun x -> print_int x)
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 := ...
// ...
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 Univ_String, Value_Type => Tree> := ...
const My_Set : Set := abc", "def", "ghi"
for each Tr">tr => Trof My_Map 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
Perl
In Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
, ''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)
Array examples:
foreach (@arr)
foreach $x (@arr)
Hash example:
foreach $x (keys %hash)
Direct modification of collection members:
@arr = ( 'remove-foo', 'remove-bar' );
foreach $x (@arr)
# Now @arr = ('foo', 'bar');
PHP
foreach ($set as $value)
It is also possible to extract both keys and values using the alternate syntax:
foreach ($set as $key => $value)
Direct modification of collection members:
$arr = array(1, 2, 3);
foreach ($arr as &$value)
// Now $arr = array(2, 3, 4);
// also works with the full syntax
foreach ($arr as $key => &$value)
More information
Python
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
A dictionary is a listing of lexemes from the lexicon of one or more specific languages, often arranged Alphabetical order, alphabetically (or by Semitic root, consonantal root for Semitic languages or radical-and-stroke sorting, radical an ...
:
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
... 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
R
for (item in object)
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))
Racket
(for ( tem 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
Array examples:
for @arr
The for loop in its statement modifier form:
.say for @arr;
for @arr -> $x
for @arr -> $x, $y
Hash example:
for keys %hash -> $key
or
for %hash.kv -> $key, $value
or
for %hash -> $x
Direct modification of collection members with a doubly pointy block, ''<->'':
my @arr = 1,2,3;
for @arr <-> $x
# Now @arr = 2,4,6;
Ruby
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
The for
loop has the structure for in . It implicitly calls th
IntoIterator::into_iter
method on the expression, and uses the resulting value, which must implement th
trait. If the expression is itself an iterator, it is used directly by the for
loop through a
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
A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
and the loop body is executed; if it returns None
, the loop is terminated.
let mut numbers = vec! , 2, 3
// Immutable reference:
for number in &numbers
for square in numbers.iter().map(, x, x * x)
// Mutable reference:
for number in &mut numbers
// prints " , 4, 6:
println!("", numbers);
// Consumes the Vec and creates an Iterator:
for number in numbers
// Errors with "borrow of moved value":
// println!("", numbers);
Scala
// return list of modified elements
items map
items map multiplyByTwo
for yield doSomething(x)
for yield multiplyByTwo(x)
// return nothing, just perform action
items foreach
items foreach println
for doSomething(x)
for println(x)
// pattern matching example in for-comprehension
for ((key, value) <- someMap) println(s"$key -> $value")
Scheme
(for-each do-something-with a-list)
do-something-with
is a one-argument function.
Smalltalk
collection do: "do something to item"
Swift
Swift uses the for
…in
construct to iterate over members of a collection.
for thing in someCollection
The for
…in
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
for i in 0...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:
A more complex example iterates over an associative array of arrays of integers:
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.
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:
Visual Basic (.NET)
For Each item In enumerable
' Do something with item.
Next
or without type inference
Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
For Each item As type In enumerable
' Do something with item.
Next
Windows
Conventional command processor
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)
From a pipeline
$list , ForEach-Object
# or using the aliases
$list , foreach
$list , %
XSLT
See also
* Do while loop
In many computer programming Programming language, languages, a do while loop is a control flow Statement (computer science), statement that executes a block of code and then either repeats the block or exits the loop depending on a given Boolea ...
* For loop
In computer science, a for-loop or for loop is a control flow Statement (computer science), statement for specifying iteration. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfi ...
* While loop
* Map (higher-order function)
In many programming languages, map is a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply-to-all'' wh ...
References
{{Reflist, 2
Control flow
Iteration in programming
Programming language comparisons
Articles with example Ada code
Articles with example C code
Articles with example C++ code
Articles with example C Sharp code
Articles with example D code
Articles with example Eiffel code
Articles with example Haskell code
Articles with example Java code
Articles with example JavaScript code
Articles with example Lisp (programming language) code
Articles with example MATLAB/Octave code
Articles with example Objective-C code
Articles with example OCaml code
Articles with example Pascal code
Articles with example Perl code
Articles with example PHP code
Articles with example Python (programming language) code
Articles with example R code
Articles with example Racket code
Articles with example Ruby code
Articles with example Rust code
Articles with example Scala code
Articles with example Scheme (programming language) code
Articles with example Smalltalk code
Articles with example Swift code
Articles with example Tcl code
ru:Цикл просмотра>1;2;3;4, ;
or in short way:
Array.iter print_int
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 := ...
// ...
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 Univ_String, Value_Type => Tree> := ...
const My_Set : Set := abc", "def", "ghi"
for each Tr">tr => Trof My_Map 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
Perl
In Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
, ''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)
Array examples:
foreach (@arr)
foreach $x (@arr)
Hash example:
foreach $x (keys %hash)
Direct modification of collection members:
@arr = ( 'remove-foo', 'remove-bar' );
foreach $x (@arr)
# Now @arr = ('foo', 'bar');
PHP
foreach ($set as $value)
It is also possible to extract both keys and values using the alternate syntax:
foreach ($set as $key => $value)
Direct modification of collection members:
$arr = array(1, 2, 3);
foreach ($arr as &$value)
// Now $arr = array(2, 3, 4);
// also works with the full syntax
foreach ($arr as $key => &$value)
More information
Python
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
A dictionary is a listing of lexemes from the lexicon of one or more specific languages, often arranged Alphabetical order, alphabetically (or by Semitic root, consonantal root for Semitic languages or radical-and-stroke sorting, radical an ...
:
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
... 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
R
for (item in object)
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))
Racket
(for ( tem 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
Array examples:
for @arr
The for loop in its statement modifier form:
.say for @arr;
for @arr -> $x
for @arr -> $x, $y
Hash example:
for keys %hash -> $key
or
for %hash.kv -> $key, $value
or
for %hash -> $x
Direct modification of collection members with a doubly pointy block, ''<->'':
my @arr = 1,2,3;
for @arr <-> $x
# Now @arr = 2,4,6;
Ruby
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
The for
loop has the structure for in . It implicitly calls th
IntoIterator::into_iter
method on the expression, and uses the resulting value, which must implement th
trait. If the expression is itself an iterator, it is used directly by the for
loop through a
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
A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
and the loop body is executed; if it returns None
, the loop is terminated.
let mut numbers = vec! , 2, 3
// Immutable reference:
for number in &numbers
for square in numbers.iter().map(, x, x * x)
// Mutable reference:
for number in &mut numbers
// prints " , 4, 6:
println!("", numbers);
// Consumes the Vec and creates an Iterator:
for number in numbers
// Errors with "borrow of moved value":
// println!("", numbers);
Scala
// return list of modified elements
items map
items map multiplyByTwo
for yield doSomething(x)
for yield multiplyByTwo(x)
// return nothing, just perform action
items foreach
items foreach println
for doSomething(x)
for println(x)
// pattern matching example in for-comprehension
for ((key, value) <- someMap) println(s"$key -> $value")
Scheme
(for-each do-something-with a-list)
do-something-with
is a one-argument function.
Smalltalk
collection do: "do something to item"
Swift
Swift uses the for
…in
construct to iterate over members of a collection.
for thing in someCollection
The for
…in
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
for i in 0...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:
A more complex example iterates over an associative array of arrays of integers:
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.
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:
Visual Basic (.NET)
For Each item In enumerable
' Do something with item.
Next
or without type inference
Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
For Each item As type In enumerable
' Do something with item.
Next
Windows
Conventional command processor
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)
From a pipeline
$list , ForEach-Object
# or using the aliases
$list , foreach
$list , %
XSLT
See also
* Do while loop
In many computer programming Programming language, languages, a do while loop is a control flow Statement (computer science), statement that executes a block of code and then either repeats the block or exits the loop depending on a given Boolea ...
* For loop
In computer science, a for-loop or for loop is a control flow Statement (computer science), statement for specifying iteration. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfi ...
* While loop
* Map (higher-order function)
In many programming languages, map is a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply-to-all'' wh ...
References
{{Reflist, 2
Control flow
Iteration in programming
Programming language comparisons
Articles with example Ada code
Articles with example C code
Articles with example C++ code
Articles with example C Sharp code
Articles with example D code
Articles with example Eiffel code
Articles with example Haskell code
Articles with example Java code
Articles with example JavaScript code
Articles with example Lisp (programming language) code
Articles with example MATLAB/Octave code
Articles with example Objective-C code
Articles with example OCaml code
Articles with example Pascal code
Articles with example Perl code
Articles with example PHP code
Articles with example Python (programming language) code
Articles with example R code
Articles with example Racket code
Articles with example Ruby code
Articles with example Rust code
Articles with example Scala code
Articles with example Scheme (programming language) code
Articles with example Smalltalk code
Articles with example Swift code
Articles with example Tcl code
ru:Цикл просмотра>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 := ...
// ...
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 Univ_String, Value_Type => Tree> := ...
const My_Set : Set := abc", "def", "ghi"
for each Tr">tr => Trof My_Map 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
Perl
In Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
, ''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)
Array examples:
foreach (@arr)
foreach $x (@arr)
Hash example:
foreach $x (keys %hash)
Direct modification of collection members:
@arr = ( 'remove-foo', 'remove-bar' );
foreach $x (@arr)
# Now @arr = ('foo', 'bar');
PHP
foreach ($set as $value)
It is also possible to extract both keys and values using the alternate syntax:
foreach ($set as $key => $value)
Direct modification of collection members:
$arr = array(1, 2, 3);
foreach ($arr as &$value)
// Now $arr = array(2, 3, 4);
// also works with the full syntax
foreach ($arr as $key => &$value)
More information
Python
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
A dictionary is a listing of lexemes from the lexicon of one or more specific languages, often arranged Alphabetical order, alphabetically (or by Semitic root, consonantal root for Semitic languages or radical-and-stroke sorting, radical an ...
:
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
... 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
R
for (item in object)
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))
Racket
(for ( tem 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
Array examples:
for @arr
The for loop in its statement modifier form:
.say for @arr;
for @arr -> $x
for @arr -> $x, $y
Hash example:
for keys %hash -> $key
or
for %hash.kv -> $key, $value
or
for %hash -> $x
Direct modification of collection members with a doubly pointy block, ''<->'':
my @arr = 1,2,3;
for @arr <-> $x
# Now @arr = 2,4,6;
Ruby
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
The for
loop has the structure for in . It implicitly calls th
IntoIterator::into_iter
method on the expression, and uses the resulting value, which must implement th
trait. If the expression is itself an iterator, it is used directly by the for
loop through a
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
A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated l ...
and the loop body is executed; if it returns None
, the loop is terminated.
let mut numbers = vec! , 2, 3
// Immutable reference:
for number in &numbers
for square in numbers.iter().map(, x, x * x)
// Mutable reference:
for number in &mut numbers
// prints " , 4, 6:
println!("", numbers);
// Consumes the Vec and creates an Iterator:
for number in numbers
// Errors with "borrow of moved value":
// println!("", numbers);
Scala
// return list of modified elements
items map
items map multiplyByTwo
for yield doSomething(x)
for yield multiplyByTwo(x)
// return nothing, just perform action
items foreach
items foreach println
for doSomething(x)
for println(x)
// pattern matching example in for-comprehension
for ((key, value) <- someMap) println(s"$key -> $value")
Scheme
(for-each do-something-with a-list)
do-something-with
is a one-argument function.
Smalltalk
collection do: "do something to item"
Swift
Swift uses the for
…in
construct to iterate over members of a collection.
for thing in someCollection
The for
…in
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
for i in 0...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:
A more complex example iterates over an associative array of arrays of integers:
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.
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:
Visual Basic (.NET)
For Each item In enumerable
' Do something with item.
Next
or without type inference
Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
For Each item As type In enumerable
' Do something with item.
Next
Windows
Conventional command processor
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)
From a pipeline
$list , ForEach-Object
# or using the aliases
$list , foreach
$list , %
XSLT
See also
* Do while loop
In many computer programming Programming language, languages, a do while loop is a control flow Statement (computer science), statement that executes a block of code and then either repeats the block or exits the loop depending on a given Boolea ...
* For loop
In computer science, a for-loop or for loop is a control flow Statement (computer science), statement for specifying iteration. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfi ...
* While loop
* Map (higher-order function)
In many programming languages, map is a higher-order function that applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type. It is often called ''apply-to-all'' wh ...
References
{{Reflist, 2
Control flow
Iteration in programming
Programming language comparisons
Articles with example Ada code
Articles with example C code
Articles with example C++ code
Articles with example C Sharp code
Articles with example D code
Articles with example Eiffel code
Articles with example Haskell code
Articles with example Java code
Articles with example JavaScript code
Articles with example Lisp (programming language) code
Articles with example MATLAB/Octave code
Articles with example Objective-C code
Articles with example OCaml code
Articles with example Pascal code
Articles with example Perl code
Articles with example PHP code
Articles with example Python (programming language) code
Articles with example R code
Articles with example Racket code
Articles with example Ruby code
Articles with example Rust code
Articles with example Scala code
Articles with example Scheme (programming language) code
Articles with example Smalltalk code
Articles with example Swift code
Articles with example Tcl code
ru:Цикл просмотра