foreach()

Applies a specified expression element-by-element across one or more arrays and returns the results as an array.

Syntax

foreach(OP_EXPR, ARRAY1[, ARRAY2, ...])

Parameters

OP_EXPR
The expression to apply to each element of the arrays. The current element of the first array is referenced as _1, the second array as _2, and the N-th array as _N.
ARRAY1[, ARRAY2, ...]
The arrays on which to perform element-wise operations. You can specify two or more arrays separated by commas (,).

Description

The foreach() function extracts the element at each position from the arrays, applies the expression specified in OP_EXPR, and returns all results combined into a single array.

When multiple arrays are specified, processing is based on the length of the longest array. For arrays that are shorter, null is used to fill the missing positions before the operation is applied. If a scalar value is passed as an argument instead of an array, that value is replicated to match the length of the longest array.

The return value is an array. If the input array is empty or all arguments are null, an empty array is returned.

Error codes

N/A

Usage examples

  1. Multiply elements at the same position in two arrays

    json "{}"
    | eval arr1 = array(-1, -2, -3, -4, -5), arr2 = array(1, 2, 3, 4, 5)
    | eval result = foreach(_1 * _2, arr1, arr2)
    | # result: [-1, -4, -9, -16, -25]
    
  2. Apply an operation to two arrays of different lengths (missing positions in the shorter array are filled with null)

    json "{}"
    | eval arr1 = array(10, 20, 30), arr2 = array(1, 2)
    | eval result = foreach(_1 + _2, arr1, arr2)
    | # result: [11,22,null]
    
  3. Use a scalar value as the second argument

    json "{}"
    | eval arr = array(1, 2, 3)
    | eval result = foreach(_1 * _2, arr, 10)
    | # result: [10, 20, 30]
    
  4. null input

    json "{}" | eval result = foreach(_1 + 1, null)
    | # result: []
    

Compatibility

foreach() has been available since before Sonar 4.0.