[comment]: # ({6537e63f-6537e63f})
# 1 Foreach functions

[comment]: # ({/6537e63f-6537e63f})

[comment]: # ({7b2ede5e-7b2ede5e})
#### Overview

Foreach functions return aggregate values from the history of multiple
items. Foreach functions are used in aggregate calculations.

The following foreach functions are supported:

|Function|Description|
|--------|-----------|
|*avg\_foreach*|Returns average values|
|*count\_foreach*|Returns the number of values|
|*last\_foreach*|Returns last values|
|*max\_foreach*|Returns maximum values|
|*min\_foreach*|Returns minimum values|
|*sum\_foreach*|Returns the sum of values|

Foreach functions return an array of values - one for each item. Items
are selected by using filters in the first parameter.

See [aggregate
calculations](/manual/config/items/itemtypes/calculated/aggregate) for
more details on using foreach functions.

[comment]: # ({/7b2ede5e-7b2ede5e})

[comment]: # ({8dbf7202-8dbf7202})
#### Parameters

Foreach functions support two parameters:

    foreach_function(item filter,time period)

for example:

    avg_foreach(/*/mysql.qps?[group="MySQL Servers"],5m)

[comment]: # ({/8dbf7202-8dbf7202})

[comment]: # ({737d2e38-737d2e38})
##### Item filter

The **first** parameter allows to filter the items we are interested in.
A complex filter may be used, referencing the item key, host group and
tags, as illustrated by the examples:

|Syntax example|Description|
|--------------|-----------|
|/host/key\[abc,\*\]|Matches similar items on this host.|
|/\*/key|Matches the same item of any host.|
|/\*/key?\[group="ABC" and tag="tagname:value"\]|Matches the same item of any host from the ABC group having 'tagname:value' tags.|
|/\*/key\[a,\*,c\]?\[(group="ABC" and tag="Tag1") or (group="DEF" and (tag="Tag2" or tag="Tag3:value"))\]|Matches similar items of any host from the ABC or DEF group with the respective tags.|

All referenced items must exist and collect data. Only enabled items on
enabled hosts are included in the calculations.

::: noteimportant
If the item key of a referenced item is changed,
the filter must be updated manually.
:::

Specifying a parent host group includes the parent group and all nested
host groups with their items.

[comment]: # ({/737d2e38-737d2e38})

[comment]: # ({9492c01c-9492c01c})
##### Time period

The **second** parameter allows to specify the time period for
aggregation. The time period can only be expressed as time, the amount
of values (prefixed with **\#**) is not supported.

[Supported unit symbols](/manual/appendix/suffixes) can be used in this
parameter for convenience, for example '5m' (five minutes) instead of
'300s' (300 seconds) or '1d' (one day) instead of '86400' (86400
seconds).

Timeperiod is ignored by the server if the function is *last\_foreach*
and can thus be omitted:

    last_foreach(/*/key?[group="host group"])

[comment]: # ({/9492c01c-9492c01c})
