Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Foreach loop
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Control flow statement for traversing items in a collection}} {{for|"for all" in logic (β)|Universal quantification}} [[File:For-Loop-Mint-Programming-Language-Type-2.gif|thumb|{{mono|foreach}} loops are almost always used to iterate over items in a sequence of elements.]] {{Loop constructs}}<!-- DO NOT remove. Discuss navigation concept at [[Talk:Do while loop#Helpbox experiment]] --> In [[computer programming]], '''foreach loop''' (or '''for-each loop''') is a [[control flow]] statement for traversing items in a [[Collection class|collection]]. {{mono|foreach}} is usually used in place of a standard {{mono|[[For loop|for]]}} loop [[Statement (computer science)|statement]]. Unlike other {{mono|for}} loop constructs, however, {{mono|foreach}} loops<ref>{{cite web | url=http://www.digitalmars.com/d/statement.html#ForeachStatement | title=D Programming Language <code>foreach</code> Statement Documentation | access-date=2008-08-04 | publisher=Digital Mars }}</ref> usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this {{mono|x}} times". This avoids potential [[off-by-one error]]s and makes code simpler to read. In [[object-oriented]] languages, an [[iterator]], even if implicit, is often used as the means of traversal. The {{mono|foreach}} statement in some languages has some defined order, processing each item in the collection from the first to the last. The {{mono|foreach}} statement in many other languages, especially [[array programming]] languages, does not have any particular order. This simplifies [[loop optimization]] in general and in particular allows [[vector processing]] of items in the collection concurrently.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)