> ## Documentation Index
> Fetch the complete documentation index at: https://docs.superoffice.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Loops - foreach

A `foreach` loop is a control structure for repeating a block of code a number of times. It will run as long as there are more elements in the collection.

The definition has 5 parts:

* keyword **foreach**
* initialization enclosed in parentheses:
  * declaration of the loop variable
  * keyword **in**
  * collection to iterate
* 1 or more statements enclosed in curly brackets

```crmscript! theme={null}
String[] mTwain;
mTwain.pushBack("The secret");
mTwain.pushBack("of");
mTwain.pushBack("getting ahead");
mTwain.pushBack("is");
mTwain.pushBack("getting started");

foreach (String s in mTwain) {
  print(s + " ");
}
```

## Initialization

The statement in the parenthesis initializes the iterator variable for the loop. The iterator must be declared as the same type as the collection. For example, if your array is of type String, then the iterator must be a string as well.

You can loop through any type of collection with `foreach`, even your own [structs][1].

## Usage

You should use a `foreach` loop when you would use a `for` loop with the following pattern:

```crmscript theme={null}
for (Integer i = 0; i < array.length(); i++) {
 print(array[i]);
}
```

This is a more compact structure that and handles the indexing for you. It is also faster!

<Note>
  The foreach statement is used to iterate through the array to get the information that you want, but can not be used to add or remove items from the source array to avoid unpredictable side effects.<br />Arrays of intrinsic types, such as String or Integer, are passed by value, while an array or a struct is passed by reference. Therefore, while inside a `foreach` loop, you can update a struct property, but not a String value.
</Note>

[1]: ./structs


## Related topics

- [Loops - for](/en/automation/crmscript/fundamentals/for-loops.md)
- [Loops - while](/en/automation/crmscript/fundamentals/while-loops.md)
- [Loops - break and continue](/en/automation/crmscript/fundamentals/loop-control.md)
- [Arrays](/en/automation/crmscript/fundamentals/arrays.md)
- [Fundamentals of CRMScript](/en/automation/crmscript/fundamentals/index.md)
- [File](/en/automation/crmscript/reference/CRMScript.Native.File.md)
