This article will cover the syntax of the ‘for each… next’ control script statement

This is an iterative statement where single or multiple parameters can be specified. The statement will loop through all the parameters and execute the script part inside the statement for each one. 

Statement syntax

for each var in list [statements] 
[exit for [ ( when | unless ) condition ] [statements] 
next [var]



Var

This is the script variable. The script will loop through the variable values.

In List

The list of variables can be a comma separated list of values. It could also be an expression resulting in multiple values such as ‘FieldValueList’.

Statements

These are statements to be executed during the script loop.

Exit for

The ‘exit for’ statement will force exit the loop. The execution will move to the first statement after the control statement.

When | Unless

The ‘exit for’ can be made conditional by using when/ unless to specify a condition for exit.

Condition

This is the condition that must be met to exit the control statement if used with the when/ unless clause. It must evaluate to True or False.

Example

This example created a list of names in a single inline field. The ‘for each… next’ statement splits the field into the first name and last name fields by delimiting using a space. The original table is then dropped.

NAMES:
LOAD * INLINE [
  Name
  John Smith
  Alan Jacob
  Maria Sampson
  ];
FOR EACH a in FieldValueList('Name')
LOAD 
    SubField('$(a)', ' ', 1) as [First Name],
    SubField('$(a)', ' ', -1) as [Last Name] 
AutoGenerate 1;
NEXT a 
DROP TABLE NAMES;

Result

The result is a single table containing 2 fields: the first name and last name.