Opentopia Directory Encyclopedia Tools

Foreach

Encyclopedia : F : FO : FOR : Foreach


For each (or foreach) is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for statement. Unlike this for loop construct however, a foreach loop usually does not specify the order in which the items are considered.

Examples

Pseudocode

In pseudocode, a foreach loop uses syntax similar to

foreach object-type object-name in collection-of-objects
DoSomething(object-name)

foreach (String person in employees)
Console.WriteLine(person);

for (String person : employees)
System.out.println(person);
Note that this requires that the Collection over which you are iterating (employees, here) is declared with a generic and each element of the Collection can be safely casted to the class of the temporary object (String, here).

for (var person in employees) 
Note that this will iterate over all properties of the employees object (e.g. the length property).

foreach my $person (@employees) 
Also, the default variable ($_) can be used:
foreach (@employees) 

foreach ($employees as $person) 
or
foreach ($array as $key => $value) 

for each aPerson as Person in employees
MsgBox aPerson.Name
next aPerson

employees.each \n"
}

Others

Other languages with support for foreach loops:

 


From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.

Search Titles
0123456789
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ?

E-mail this article to:

Personal Message: