Foreach

From Free net encyclopedia

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 loop. Unlike this for loop construct however, a foreach loop usually does not specify the order in which the items are considered.

Contents

Examples

Pseudocode

In pseudocode, a foreach loop uses syntax similar to

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

C#

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

Java starting with version J2SE 5.0

for (String person : employees)
    System.out.println(person);

Javascript

for (var person in employees) {
    document.write(person);
}

Perl

foreach my $person (@employees) {
    print "$person\n";
}

PHP

foreach ($employees as $person) {
   echo "$person\n";
}
foreach ($employees as $id => $person) {
   echo "$id: $person\n"; //$id refers to the key of the array at $person
}

REALbasic

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

Others

Other languages with support for foreach loops: