Home

forEach

Foreach is a control flow construct used in many programming languages to iterate over the elements of a collection, such as arrays, lists, or maps. The loop applies a block of code to each element in the sequence, typically abstracting away manual index handling and boundary checks.

Syntax and language variations are common. In Java and C#, for example, a common form is for

Semantics can differ regarding modification. In many languages, the loop variable yields a value that does

Advantages of foreach include improved readability, reduced risk of off-by-one errors, and a concise pattern for

Common uses are applying transformations or actions to each element, iterating over maps or key-value pairs,

(Type
item
:
collection)
{
...
}
or
foreach
(Type
item
in
collection)
{
...
}.
PHP
uses
foreach
($array
as
$value)
{
...
}
and
can
also
expose
keys.
JavaScript
offers
a
for...of
form
(for
(const
item
of
array)
{
...
})
and,
alternatively,
Array.prototype.forEach.
Python
uses
for
item
in
collection:
{
...
}.
While
the
exact
syntax
differs,
the
underlying
idea
is
consistent:
obtain
each
element
in
turn
and
execute
the
loop
body.
not
automatically
modify
the
original
collection,
and
updating
elements
may
require
special
syntax
or
additional
indexing.
Some
languages
allow
iterating
by
reference
or
provide
means
to
modify
the
underlying
collection
during
iteration,
while
others
prohibit
structural
changes
to
the
collection
while
iterating.
applying
an
operation
to
every
element.
Limitations
include
limited
access
to
element
indices
(unless
the
language
provides
a
way
to
obtain
them)
and
potential
difficulties
when
the
collection
should
be
modified
structurally
during
iteration.
and
performing
operations
without
explicit
index
management.
Foreach
is
widely
supported,
with
language-specific
variations
and
terminology
such
as
for-each
or
foreach.