Questions tagged [foreach]

foreach is a looping construct that executes a given piece of code for each element in a list/collection/array. In contrast to a for loop, the foreach loop doesn't require the coder to maintain a counter variable to avoid off-by-one (fencepost) bugs. It is recommended to use when simple iteration over whole array/list/collection is needed.

The foreach statement repeats a group of embedded statements for each element in an array or object collection.

The foreach statement is used to iterate through the collection, but can not be used to add or remove items from the source collection, which could cause unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

Some form of the foreach loop is supported by most languages, though the syntax may differ greatly. Here are a few examples (to be extended):

C#

foreach (var element in Collection)

Java

for (SomeType element : collection)

JavaScript

for (element in collection)

Haxe

for (element in iterable)

PHP

foreach($collection as $key => $value)

Visual Basic .NET

For Each Element As SomeType In Collection
    ...
Next

VBA

For Each Element In Group
    ...
Next

C++ (Since C++11)

for (auto i : collection )

Objective-C

for (id object in list)

Swift

for (item in list)

Awk

for (i in a)

Perl

for my $element (@array)

JQ

foreach stream as $var

The following languages do not natively support any kind of foreach statement:

For some languages, the foreach semantics are the basic form of a for loop. Examples include

See also: , , , and .

25613 questions
5616
votes
41 answers

Loop (for each) over an array in JavaScript

How can I loop through all the entries in an array using JavaScript?
Dante1986
  • 58,291
  • 13
  • 39
  • 54
2262
votes
7 answers

How does PHP 'foreach' actually work?

Let me prefix this by saying that I know what foreach is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of "this is how you loop an array with foreach". For a long time I…
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
2148
votes
31 answers

Short circuit Array.forEach like calling break

[1,2,3].forEach(function(el) { if(el === 1) break; }); How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
Scott Klarenbach
  • 37,171
  • 15
  • 62
  • 91
1855
votes
4 answers

Is there a reason for C#'s reuse of the variable in a foreach?

When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example: foreach (var s in strings) { query = query.Where(i => i.Prop == s); // access to modified closure ... } Due…
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
1715
votes
29 answers

How does the Java 'for each' loop work?

Consider: List someList = new ArrayList(); // add "monkey", "donkey", "skeleton key" to someList for (String item : someList) { System.out.println(item); } What would the equivalent for loop look like without using the for each…
Jay R.
  • 31,911
  • 17
  • 52
  • 61
1272
votes
37 answers

How do you get the index of the current iteration of a foreach loop?

Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop? For instance, I currently do something like this…
Matt Mitchell
  • 40,943
  • 35
  • 118
  • 185
868
votes
22 answers

LINQ equivalent of foreach for IEnumerable

I'd like to do the equivalent of the following in LINQ, but I can't figure out how: IEnumerable items = GetItems(); items.ForEach(i => i.DoStuff()); What is the real syntax?
tags2k
  • 82,117
  • 31
  • 79
  • 106
763
votes
9 answers

Is there a foreach loop in Go?

Is there a foreach construct in the Go language? Can I iterate over a slice or array using a for?
tatsuhirosatou
  • 25,149
  • 14
  • 39
  • 40
671
votes
11 answers

Calling remove in foreach loop in Java

In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance: List names = .... for (String name : names) { // Do something names.remove(name). } As an addendum, is it…
Michael Bobick
  • 8,897
  • 5
  • 22
  • 13
647
votes
14 answers

How to find the foreach index?

Is it possible to find the foreach index? in a for loop as follows: for ($i = 0; $i < 10; ++$i) { echo $i . ' '; } $i will give you the index. Do I have to use the for loop or is there some way to get the index in the foreach loop?
user18334
  • 6,563
  • 2
  • 19
  • 7
640
votes
12 answers

Get loop counter/index using for…of syntax in JavaScript

Caution: question still applies to for…of loops.> Don't use for…in to iterate over an Array, use it to iterate over the properties of an object. That said, this I understand that the basic for…in syntax in JavaScript looks like this: for (var…
hobbes3
  • 28,078
  • 24
  • 87
  • 116
625
votes
18 answers

Update all objects in a collection using LINQ

Is there a way to do the following using LINQ? foreach (var c in collection) { c.PropertyToSet = value; } To clarify, I want to iterate through each object in a collection and then update a property on each object. My use case is I have a bunch…
lomaxx
  • 113,627
  • 57
  • 144
  • 179
612
votes
21 answers

PHP How to determine the first and last iteration in a foreach loop?

The question is simple. I have a foreach loop in my code: foreach($array as $element) { //code } In this loop, I want to react differently when we are in first or last iteration. How to do this?
mehdi
  • 9,262
  • 11
  • 35
  • 35
542
votes
19 answers

For..In loops in JavaScript - key value pairs

I was wondering if there's a way to do something like a PHP foreach loop in JavaScript. The functionality I'm looking for is something like this PHP Snippet: foreach($data as $key => $value) { } I was looking at the JS for..in loop, but there seems…
Joris Ooms
  • 11,880
  • 17
  • 67
  • 124
462
votes
11 answers

change values in array when doing foreach

example: var arr = ["one","two","three"]; arr.forEach(function(part){ part = "four"; return "four"; }) alert(arr); The array is still with it's original values, is there any way to have writing access to array's elements from iterating…
rsk82
  • 28,217
  • 50
  • 150
  • 240
1
2 3
99 100