<p>What are some different syntax choices for loops that iterate over arrays? Of course, there is the common <code>for</code> loop:</p>
<pre class="lang-java prettyprint-override"><code>for (int i = 0; i &lt; 8; ++i) {
    myArr[i]
}
</code></pre>
<p>But this isn't the only option. What are some others?</p>

<syntax><arrays><iterators>
What are some syntax options for iterating over arrays?
<p><strong>Functor fmap</strong></p>
<p>For repetitive (but not only) tasks over a structure like an Array, I like the Functional Programming point of view: map/fmap  syntax</p>
<p>The goal of it is pretty similar to foreach in imperative languages</p>
<p>If you happen to have any structure that is a candidate for being a Functor (there are only a few features to respect for this), and lists / arrays are Functors, in Haskell, you can do this:</p>
<pre><code>fmap myFunction myArray
</code></pre>
<p>Once accustomed to it, for me it is difficult to want to use something else.
myFunction can of course be a short lambda definition</p>
<pre><code>fmap (\x -&gt; x+1) myArrayOfXs
</code></pre>
<p>In case you have a computation that is more than reading or doing simple stuffs, you can also use the more elaborated mapM, but then we enter the realm of Monads. I just mention it here.</p>
<p>And finally, there's Traversable typeclass/interface to iterate over Traversable containers: not only can you iterate and have behaviour during the iterationm, but you can even create a structure issuing from the iteration.</p>

CC BY-SA 4.0
2023-05-31T06:56:13.887Z
2023-06-01T15:17:31.797Z
2023-06-01T15:17:31.797Z
Stephane Rolland
<h1>Backwards foreach</h1>
<p>PHP uses this:</p>
<pre class="lang-php prettyprint-override"><code>foreach ($arr as $el) {
  ...
}
</code></pre>
<p>I think there might also be a language that uses something like <code>foreach (arr =&gt; el)</code>, but I don't remember what.</p>

CC BY-SA 4.0
2023-05-19T17:48:32.143Z
2023-05-19T17:48:32.143Z
naffetS
CC BY-SA 4.0
2023-05-19T17:55:13.987Z
You can also use `($arr as $key=>$value)` for associative arrays
mousetail 'he-him'
<h2>Java for each</h2>
<pre class="lang-java prettyprint-override"><code>for (int item : myArr) {
    System.out.println(item);
}
</code></pre>
<p>This style is easier, as we don't need to keep track of an iterator variable (like <code>i</code>), and instead we can work directly with <code>item</code> instead. It does come with a tradeoff when <code>item</code> is a <em>copy</em> of an item in <code>myArr</code>, as we can't easily modify the original array</p>
<pre class="lang-java prettyprint-override"><code>for (int item : myArr) {
    // this changes item, but not the original item in myArr
    item = 0;
}
</code></pre>

CC BY-SA 4.0
2023-05-19T17:21:41.713Z
2023-05-19T17:21:41.713Z
cocomac
CC BY-SA 4.0
2023-05-19T18:15:22.047Z
"*It does come with a tradeoff when item is a copy of an item in myArr, as we can't easily modify the original array*" that's true in Java but does not have to be true in general: `item` might be a reference to the array slot, thus `item = 0` could directly manipulate the array. I don't know of any language that does this with a for-each but it still could be done.
VLAZ
CC BY-SA 4.0
2023-06-12T13:04:04.487Z
@VLAZ-onstrike- I think rust can do that with `iter_mut`
Seggan
CC BY-SA 4.0
2023-06-12T13:07:08.543Z
C++ has that, `for (int& item : arr)`. In fact, I've seen at least as much "borrowing" `for (const auto& item : arr)` as I have copying `for (auto item : arr)`.
Bbrk24
CC BY-SA 4.0
2023-07-03T20:15:15.857Z
@VLAZ-onstrike- PHP does that in `foreach ($arr as &$item) {}`: the `&` indicates using a reference. You do need to `unset($item)` at the end of the loop or you get weirdness.
TRiG
<h1>for range</h1>
<p><a href="https://go.dev/tour/moretypes/16" rel="nofollow noreferrer">https://go.dev/tour/moretypes/16</a></p>

<pre class="lang-go prettyprint-override"><code>for index, value := range data {
    fmt.Printf(&quot;2**%d = %d\n&quot;, index, value)
}
</code></pre>

CC BY-SA 4.0
2023-05-19T20:34:47.883Z
2023-07-30T18:46:34.397Z
2023-07-30T18:46:34.397Z
OscarRyz
<h1>Generator Functions</h1>
<pre class="lang-lua prettyprint-override"><code>for key, value in pairs(table) do
    print(value)
end
</code></pre>
<p><a href="https://www.lua.org/pil/7.3.html" rel="nofollow noreferrer">Lua</a> doesn't support table iteration as a keyword directly, instead relying on generators to do the heavy lifting.</p>
<p>This is notably different from languages like Python and C# in that the <code>for</code> keyword does not support directly iterating over any object, only generator functions.</p>

CC BY-SA 4.0
2023-07-30T22:59:53.960Z
2023-07-30T22:59:53.960Z
ATaco
<h1>C# foreach</h1>
<pre class="lang-cs prettyprint-override"><code>foreach (int number in Numbers) {
    ...
}
</code></pre>

CC BY-SA 4.0
2023-06-01T10:02:44.607Z
2023-06-01T10:02:44.607Z
чистов_n
CC BY-SA 4.0
2023-06-01T13:57:36.400Z
Isn't this essentially the same as [Java](https://languagedesign.stackexchange.com/a/704/7)?
Adám
CC BY-SA 4.0
2023-07-30T16:43:35.587Z
@Adám - no, as it uses an additional keyword `in` rather than punctuation `:`.  There are pros and cons for the two choices, so it's worth listing both.
occipita
<h1>Iterating over multiple arrays together, and in fixed-size chunks</h1>
<p>Below are quoted from the Tcl man page. Note that in Tcl, arrays are read into a list in a single level by the format <code>{key value key value ...}</code> that odd elements are keys, and even elements are values, which is probably why it would be helpful to iterate in chunks. The part about iterating over multiple arrays would be much more useful in other languages. It also has a variant version <code>lmap</code> which works like <code>foreach</code> but also collects the result. <code>{}</code> denotes an empty string.</p>
<p>The following loop uses <code>i</code> and <code>j</code> as loop variables to iterate over pairs        of elements of a single list.</p>
<pre><code>set x {}
foreach {i j} {a b c d e f} {
    lappend x $j $i
}
# The value of x is &quot;b a d c f e&quot;
# There are 3 iterations of the loop.
</code></pre>
<p>The next loop uses <code>i</code> and <code>j</code> to iterate over two lists in parallel.</p>
<pre><code>set x {}
foreach i {a b c} j {d e f g} {
    lappend x $i $j
}
# The value of x is &quot;a d b e c f {} g&quot;
# There are 4 iterations of the loop.
</code></pre>
<p>The two forms are combined in the following example.</p>
<pre><code>set x {}
foreach i {a b c} {j k} {d e f g} {
    lappend x $i $j $k
}
# The value of x is &quot;a d e b f g c {} {}&quot;
# There are 3 iterations of the loop.
</code></pre>

CC BY-SA 4.0
2023-07-30T12:08:53.800Z
2023-07-30T12:08:53.800Z
user23013
<p>Functional languages may have a higher-order function (not a list method!) which takes a function/lambda/operator and one (or more!) arrays, and iterates over them. E.g. APL and BQN have <em>Each</em> (<code>¨</code>) which, together with <em>Take</em> (<code>↑</code>) allows us to take various prefixes from a corresponding number of strings:</p>
<pre><code>      3 1 4↑¨'Hello' 'There' 'World'
┌───┬─┬────┐
│Hel│T│Worl│
└───┴─┴────┘
</code></pre>
<p>We can of course also use it with a single list, here with Reverse (<code>⌽</code>):</p>
<pre><code>      ⌽¨'Hello' 'There' 'World'
┌─────┬─────┬─────┐
│olleH│erehT│dlroW│
└─────┴─────┴─────┘
</code></pre>
<p>Note that <code>¨</code> is not something built into the lists, as we can assign the result of <code>¨</code> combining with an operation:</p>
<pre><code>      ReverseEach←⌽¨
      ReverseEach 'Hello' 'There' 'World'
┌─────┬─────┬─────┐
│olleH│erehT│dlroW│
└─────┴─────┴─────┘
</code></pre>

CC BY-SA 4.0
2023-05-19T17:36:29.580Z
2023-05-19T17:36:29.580Z
Adám
<h1>for-in</h1>
<p>This is the approach taken by Swift and Python:</p>
<pre class="lang-swift prettyprint-override"><code>for el in arr {
  print(el)
}
</code></pre>
<p>JS does something similar, but for historical reasons it uses <code>of</code> instead:</p>
<pre class="lang-js prettyprint-override"><code>for (const el of arr)
  console.log(el);
</code></pre>

CC BY-SA 4.0
2023-05-19T17:33:07.933Z
2023-05-19T17:33:07.933Z
Bbrk24
CC BY-SA 4.0
2023-05-19T17:42:55.720Z
It's confusing in JS because `in` actually loops over the keys
naffetS
CC BY-SA 4.0
2023-05-19T17:44:18.567Z
PHP uses `foreach ($arr as $el)`, which is backwards
naffetS
CC BY-SA 4.0
2023-05-19T17:45:34.947Z
PHP's syntax should probably be its own answer, then.
Bbrk24
CC BY-SA 4.0
2023-06-01T11:54:48.970Z
JS `for...of` uses `[Symbol.iterator]` as the iterator too
Hydroper
CC BY-SA 4.0
2023-06-12T13:03:24.280Z
And Rust... and Kotlin...
Seggan
<h1>For each function</h1>
<p>Some languages have a ‘forEach‘ function on their lists that takes a list and a lambda, and applies that lambda to each item. For example, Kotlin:</p>
<pre><code>list.forEach { item -&gt; 
    println(item) 
}
</code></pre>

CC BY-SA 4.0
2023-05-19T17:23:44.070Z
2023-05-19T17:23:44.070Z
Seggan
CC BY-SA 4.0
2023-05-19T18:28:22.843Z
This also exists in JavaScript
Jacob
# What are some syntax options for iterating over arrays?
Posted by: username_0 on 2023-05-19
What are some different syntax choices for loops that iterate over arrays? Of course, there is the common for loop:
for (int i = 0; i < 8; ++i) {
    myArr[i]
}

But this isn't the only option. What are some others?
**Tags:** syntax arrays iterators
---
## 10 answers
### Answer by username_11 on 2023-05-19. Score: 11
Functional languages may have a higher-order function (not a list method!) which takes a function/lambda/operator and one (or more!) arrays, and iterates over them. E.g. APL and BQN have Each (¨) which, together with Take (↑) allows us to take various prefixes from a corresponding number of strings:
      3 1 4↑¨'Hello' 'There' 'World'
┌───┬─┬────┐
│Hel│T│Worl│
└───┴─┴────┘

We can of course also use it with a single list, here with Reverse (⌽):
      ⌽¨'Hello' 'There' 'World'
┌─────┬─────┬─────┐
│olleH│erehT│dlroW│
└─────┴─────┴─────┘

Note that ¨ is not something built into the lists, as we can assign the result of ¨ combining with an operation:
      ReverseEach←⌽¨
      ReverseEach 'Hello' 'There' 'World'
┌─────┬─────┬─────┐
│olleH│erehT│dlroW│
└─────┴─────┴─────┘
---
### Answer by username_6 on 2023-05-19. Score: 9
for-in
This is the approach taken by Swift and Python:
for el in arr {
  print(el)
}

JS does something similar, but for historical reasons it uses of instead:
for (const el of arr)
  console.log(el);
> **Comments:**
> **username_2** (2023-05-19): It's confusing in JS because `in` actually loops over the keys  
> **username_2** (2023-05-19): PHP uses `foreach ($arr as $el)`, which is backwards  
> **username_6** (2023-05-19): PHP's syntax should probably be its own answer, then.  
> **username_14** (2023-06-01): JS `for...of` uses `[Symbol.iterator]` as the iterator too  
> **username_5** (2023-06-12): And Rust... and Kotlin...  
---
### Answer by username_5 on 2023-05-19. Score: 9
For each function
Some languages have a ‘forEach‘ function on their lists that takes a list and a lambda, and applies that lambda to each item. For example, Kotlin:
list.forEach { item -> 
    println(item) 
}
> **Comments:**
> **username_15** (2023-05-19): This also exists in JavaScript  
---
### Answer by username_1 on 2023-05-31. Score: 6
Functor fmap
For repetitive (but not only) tasks over a structure like an Array, I like the Functional Programming point of view: map/fmap  syntax
The goal of it is pretty similar to foreach in imperative languages
If you happen to have any structure that is a candidate for being a Functor (there are only a few features to respect for this), and lists / arrays are Functors, in Haskell, you can do this:
fmap myFunction myArray

Once accustomed to it, for me it is difficult to want to use something else.
myFunction can of course be a short lambda definition
fmap (\x -> x+1) myArrayOfXs

In case you have a computation that is more than reading or doing simple stuffs, you can also use the more elaborated mapM, but then we enter the realm of Monads. I just mention it here.
And finally, there's Traversable typeclass/interface to iterate over Traversable containers: not only can you iterate and have behaviour during the iterationm, but you can even create a structure issuing from the iteration.
---
### Answer by username_2 on 2023-05-19. Score: 4
Backwards foreach
PHP uses this:
foreach ($arr as $el) {
  ...
}

I think there might also be a language that uses something like foreach (arr => el), but I don't remember what.
> **Comments:**
> **username_3** (2023-05-19): You can also use `($arr as $key=>$value)` for associative arrays  
---
### Answer by username_0 on 2023-05-19. Score: 4
Java for each
for (int item : myArr) {
    System.out.println(item);
}

This style is easier, as we don't need to keep track of an iterator variable (like i), and instead we can work directly with item instead. It does come with a tradeoff when item is a copy of an item in myArr, as we can't easily modify the original array
for (int item : myArr) {
    // this changes item, but not the original item in myArr
    item = 0;
}
> **Comments:**
> **username_4** (2023-05-19): "*It does come with a tradeoff when item is a copy of an item in myArr, as we can't easily modify the original array*" that's true in Java but does not have to be true in general: `item` might be a reference to the array slot, thus `item = 0` could directly manipulate the array. I don't know of any language that does this with a for-each but it still could be done.  
> **username_5** (2023-06-12): @VLAZ-onstrike- I think rust can do that with `iter_mut`  
> **username_6** (2023-06-12): C++ has that, `for (int& item : arr)`. In fact, I've seen at least as much "borrowing" `for (const auto& item : arr)` as I have copying `for (auto item : arr)`.  
> **username_7** (2023-07-03): @VLAZ-onstrike- PHP does that in `foreach ($arr as &$item) {}`: the `&` indicates using a reference. You do need to `unset($item)` at the end of the loop or you get weirdness.  
---
### Answer by username_8 on 2023-05-19. Score: 4
for range
https://go.dev/tour/moretypes/16
for index, value := range data {
    fmt.Printf("2**%d = %d\n", index, value)
}
---
### Answer by username_13 on 2023-07-30. Score: 3
Iterating over multiple arrays together, and in fixed-size chunks
Below are quoted from the Tcl man page. Note that in Tcl, arrays are read into a list in a single level by the format {key value key value ...} that odd elements are keys, and even elements are values, which is probably why it would be helpful to iterate in chunks. The part about iterating over multiple arrays would be much more useful in other languages. It also has a variant version lmap which works like foreach but also collects the result. {} denotes an empty string.
The following loop uses i and j as loop variables to iterate over pairs        of elements of a single list.
set x {}
foreach {i j} {a b c d e f} {
    lappend x $j $i
}
# The value of x is "b a d c f e"
# There are 3 iterations of the loop.

The next loop uses i and j to iterate over two lists in parallel.
set x {}
foreach i {a b c} j {d e f g} {
    lappend x $i $j
}
# The value of x is "a d b e c f {} g"
# There are 4 iterations of the loop.

The two forms are combined in the following example.
set x {}
foreach i {a b c} {j k} {d e f g} {
    lappend x $i $j $k
}
# The value of x is "a d e b f g c {} {}"
# There are 3 iterations of the loop.
---
### Answer by username_9 on 2023-07-30. Score: 2
Generator Functions
for key, value in pairs(table) do
    print(value)
end

Lua doesn't support table iteration as a keyword directly, instead relying on generators to do the heavy lifting.
This is notably different from languages like Python and C# in that the for keyword does not support directly iterating over any object, only generator functions.
---
### Answer by username_10 on 2023-06-01. Score: 2
C# foreach
foreach (int number in Numbers) {
    ...
}
> **Comments:**
> **username_11** (2023-06-01): Isn't this essentially the same as [Java](https://languagedesign.stackexchange.com/a/704/7)?  
> **username_12** (2023-07-30): @Adám - no, as it uses an additional keyword `in` rather than punctuation `:`.  There are pros and cons for the two choices, so it's worth listing both.  
---
