---
title: "foreach — For each loop"
description: "iXML command foreach: For each loop."
canonical_url: "https://www.zeyos.com/ixml/ref/foreach"
markdown_url: "https://www.zeyos.com/ai/guide/ixml/ref/foreach.md"
section: "ixml-reference"
authority: "reference"
language: "en"
source_repository: "https://cloud.zeyos.com/__doc/ixmldoc.xml"
source_sha256: "a23f04e6a98628ca3c273c3b8dd2c33c034cfda3e0f00478d8793074fd2f70dd"
---

# foreach — For each loop

The FOREACH construct is a control flow structure for traversing items in a collection by iterating over an array, populating the associated key and value pairs for each item.

On each loop iteration, the embedded code is executed with the key of the current item assigned to 'var_key' and the value of the current item assigned to 'var_value'.

### Attributes
| Name | Type | Default | Description |
| ---- | ---- | ------- | ----------- |
| var | var |  | Source variable name |
| var_key | var |  | Variable name for key |
| var_value | var |  | Variable name for value |

### Children
- else (occurrence: single) — Elsewise execution

### Parents
- (not restricted in the reference)

### Result
- (none documented)

### Examples

```xml
<array var="names">
	<item>Bill Gates</item>
	<item>Steve Jobs</item>
</array>

<foreach var="names" var_value="name">
	<output>$name&n;</output>
</foreach>

<!--
Bill Gates
Steve Jobs
-->
```

```xml
<array var="names">
	<item>Bill Gates</item>
	<item>Steve Jobs</item>
</array>

<foreach var="names" var_key="key" var_value="name">
	<if value1="$name" func="=" value2="Bill Gates">
		<set var="names[$key]">William Henry Gates III</set>
	</if>
</foreach>

<output>
	<array:join var="names" delimiter=", "/>
</output>

<!-- William Henry Gates III, Steve Jobs -->
```

```xml
<array var="names">
	<array>
		<item key="firstname">Bill</item>
		<item key="lastname">Gates</item>
	</array>
	<array>
		<item key="firstname">Steve</item>
		<item key="lastname">Jobs</item>
	</array>
</array>

<foreach var="names" var_value="name">
	<if value1="$name.lastname" func="=" value2="Gates">
		<set var="name.fullname">William Henry Gates III</set>
	</if>
</foreach>

<output>$names[0].fullname</output>

<!-- William Henry Gates III -->
```

```xml
<array var="names">
	<item>Bill Gates</item>
	<item>Steve Jobs</item>
</array>

<foreach var="names" var_value="name">
	<output>$name</output>

	<if value1="$name" func="=" value2="Bill Gates">
		<break/>
	</if>
</foreach>

<!-- Bill Gates -->
```

```xml
<array var="names">
	<item>Bill Gates</item>
	<item>Steve Jobs</item>
</array>

<foreach var="names" var_value="name">
	<if value1="$name" func="=" value2="Bill Gates">
		<next/>
	</if>

	<output>$name</output>
</foreach>

<!-- Steve Jobs -->
```
