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 |
[edit]
Examples
[edit]
Pseudocode
In pseudocode, a foreach loop uses syntax similar to
foreach object-type object-name in collection-of-objects DoSomething(object-name)
[edit]
C#
foreach (String person in employees) Console.WriteLine(person);
[edit]
Java starting with version J2SE 5.0
for (String person : employees) System.out.println(person);
[edit]
Javascript
for (var person in employees) { document.write(person); }
[edit]
Perl
foreach my $person (@employees) { print "$person\n"; }
[edit]
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 }
[edit]
REALbasic
for each aPerson as Person in employees MsgBox aPerson.Name next aPerson
[edit]
Others
Other languages with support for foreach loops:
- Visual Basic
- Tcl
- Python
- tcsh
- Smalltalk do:
- JavaScript's For in loop can be used in a similar manner to a foreach loop. Likewise in Bourne shell.ja:Foreach文