Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

ArgumentTypeDescription
$var

$-variable

A $-variable which will be set to each item in set in turn before script is processed.
setArray or RecordsetThe set of items which will be iterated over.
script$-variableA comma-separated list of expressions which will be processed once for each entry in set.

forEach() is like every other function in that it returns a value.: 

  • Its return value is a list containing the last statement executed in the last each iteration.
  • All the $-variables used in the call to forEach() keep their values between iterations.
  • All the $-variables used in the call to forEach() will be available after it has returned.

...

Use in Conjunction With

  • continue, will continue to the next item in the set.
  • break, will break out of the forEach loop. 

Examples


In the first two examples, let

...

Code Block
forEach($number, $numberList, 

   $currentValue = $number*2

),

Returns [2,4,6,8,10,12,14,16,18,20], as forEach() returns the value of the final expression to be evaluated in its final each iteration.


Code Block
do(
  forEach($number, $numberList,   
   $sumOfNumbers = $sumOfNumbers + $number
  ),
  $sumOfNumbers
)

Returns 55. The forEach will return the value at each iteration ([1, 3, 6, 10, 15, 21, 28, 36, 45, 55, as the variable $sumOfNumbers persists in-between forEach iterations]), the do then returns the final value of $sumOfNumbers.

Detailed example: (step-by-step)

Code Block
forEach( $customerType, customers.type, 

   $total = $total + 1, 

   if( $customerType == "Business", continue() ), 

   $nonBusiness = $nonBusiness + 1, 

   subString($customerType, 1, 6) 
)

...

  1. Assign the value of the customer type to the $-Variable $customerType.
  2. The first expression then increments the value of $total by 1 (i.e. counting the total number of types in the list).
  3. The second expression checks if the type is "Business" and if so calls continue() which causes forEach() to immediately skip to the next customer type in customers.type and starts again from the first expression (i.e. it does not reach the 3rd expression to increment the $-Variable $nonBusiness).
  4. If the type is not "Business" the third expression will be processed increment incrementing a count of the non-business types.
  5. The final expression is evaluated and the result added to the result Array of the forEach() function.

...