A process loop enables code or content within a block to be repeated until an ending index expression is reached. There are seven required parts in a process loop:
- an opening
- a loop counter, defined as a variable
- a starting index expression
- a direction keyword; either
to(to increase) or
- an ending index expression
for statement initializes the process loop. The scope of counter variable is different from other AMPscript variables (which have a local scope). This variable is set as a global scope and is locked from modification within the process loop.
NOTE: The counter variable is locked from modification within a process loop. Any attempt to declare it will result in a validation or runtime error.
The start and end index expressions must evaluate to an integer (not a decimal) and can use one of the following input types:
- a numeric constant
- an attribute or Data Extension value
- a variable
- a function
The direction keyword determines whether the value of the variable increases or decreases by one with each iteration of the
for loop. The variable value sets or increments by one after each iteration of the loop.
next statement closes the
for loop. When the
next keyword is reached, the system compares the end index expression to the value of the counter variable. If the value is not equal to the end index, the loop will repeat until the end index is reached.
The following example sets the starting index as
1 and the ending index as
next statement can be followed with the counter variable name:
A common use case for AMPscript process loops is to look up multiple values from a Data Extension for a Contact or Subscriber; for example order line items to include in an order confirmation email.
The following code retrieves ‘Name’ and ‘Price’ fields from a Data Extension for rows that match an order number attribute. The number of matching rows is counted using the RowCount function and the field values are displayed as list items for the returned rows.