Technology
 

For Each loop

From Programmer's Wiki

For Each loops are used for iterating over the items in a collection.

Contents

[edit] Introduction

For loops provide an easy way to traverse arrays. as part of the loop a variable is created that is incremented after each loop is completed. This variable can be used as the index to an array as well. However if the loop is just making a modification to each item then this method is often a clumsy way of expressing the programmers intentions. The For Each loop simplifies this by exposing each item without needing to know it's position in the list.


The collection objects must support the appropriate interface (as defined by the language).

[edit] Groovy

In groovy the each method can be used as a for each loop.

[1,2,3,4].each{
    println it
}

Also the for loop can be used on collections

def list = [1,2,3,4]

for(item in list){
    println item
}


[edit] PHP

Simple foreach loop:

// create an array containing some numbers
$arr = array(1, 2, 3, 4, 5);
//print every number
foreach ($arr as $number) {
    echo "$number<br/>";
}

Foreach for associative array:

// create an associative array
$arr['name'] = "Katy";
$arr['surname'] = "Jones":
$arr['age'] = 29;
// print $arr's key (name, etc) and values ("Katy", etc)
foreach ($arr as $key => $value) {
    echo "<strong>$key</strong>: $value<br/>";
}

[edit] Visual Basic

Any object that implements the IEnumerable, ICollection, or their generic counterparts, including arrays, can be traversed by a For Each loop.

Dim x As New List(Of String)
x.Add("corn")
x.Add("coconut")
x.Add("lemons")
For Each item As String In x
    Console.Write(item)
Next

The type declaration can be omitted if Option Infer is set. In IEnumerable implementations, the traversal of the collection can be customized by customizing the corresponding IEnumerator.

[edit] Javascript

var item;
var x = new Array();

x[0] = "apples";
x[1] = "oranges";
x[2] = "books";

for (item in x)
{
    document.write(x[item] + "<br />");
}
Control structures
If statement - Switch statement - While loop - For loop - For Each loop - Do while loop