---
title: Running an action for each element in an array
description: You can use the foreach field in an action to trigger the configured action for every element within that array. In order to protect from long running...
url: https://docs-v3-preview.elastic.dev/elastic/docs-content/pull/1655/explore-analyze/alerts-cases/watcher/action-foreach
products:
  - Elasticsearch
---

# Running an action for each element in an array
You can use the `foreach` field in an action to trigger the configured action for every element within that array.
In order to protect from long running watches, you can use the `max_iterations` field to limit the maximum amount of runs that each watch executes. If this limit is reached, the execution is gracefully stopped. If not set, this field defaults to one hundred.
```json

{
  "trigger" : {
    "schedule" : { "interval" : "5m" }
  },
  "input" : {
    "search" : {
      "request" : {
        "indices" : "log-events",
        "body" : {
          "query" : { "match" : { "status" : "error" } }
        }
      }
    }
  },
  "condition" : {
    "compare" : { "ctx.payload.hits.total" : { "gt" : 0 } }
  },
  "actions" : {
    "log_hits" : {
      "foreach" : "ctx.payload.hits.hits", <1>
      "max_iterations" : 500,
      "logging" : {
        "text" : "Found id {{ctx.payload._id}} with field {{ctx.payload._source.my_field}}"
      }
    }
  }
}
```

<note>
  If you are running a [`script`](https://docs-v3-preview.elastic.dev/elastic/docs-content/pull/1655/explore-analyze/alerts-cases/watcher/transform-script) payload transform, the transform needs to be included prior to the `actions` section to ensure the output is available to the `foreach` loop.
</note>