Page tree
Skip to end of metadata
Go to start of metadata

Introduced in



Description:Executes the given command(s) on every item of an array.

The current array item (the item being iterated over) is represented by _x, to be used in the command block. The variable _x is always local to the forEach block, so it is safe to nest them.

V2.0+: The variable _forEachIndex is also available, and indicates the (0-based) index number of the currently active element. For example:

{player sidechat format["forEachIndex: %1 = _x: %2",_forEachIndex,_x]}forEach ["A","B","C"]; 
// Creates the output:
// "forEachIndex: 0 = _x: A"
// "forEachIndex: 1 = _x: B"
// "forEachIndex: 2 = _x: C"


Syntax:command forEach array
  • command: String - Command to execute for each element in array. Variable _x (which contains the current element) can be used in the command.
  • array: Array - List of elements to cycle through.
Return Value:Nothing


{_x setdammage 1} forEach units group player

// Multiple commands can be executed in the same block
{_x setCaptive true; removeAllWeapons _x; doStop _x;} forEach units group this

// Can also be used to execute a single command multiple times, irrespective of array items
{player addMagazine "M16"} forEach [1,2,3,4]

Additional Information

See also: count, Control Structures


Posted on July 20, 2010
If arrays are used in forEach loops, _x uses them by reference, so any changes to _x will be applied to the original:

_arr1 = [1,2,3];
_arr2 = [6,7,8];
{_x set [1,"x"]} forEach [_arr1,_arr2];

will change _arr1 to [1,"x",3], and _arr2 to [6,"x",8].