For Loops
Use For
loops to iterate through data structures or execute code a certain number of times.
At a minimum, a For
statement must include:
- The keyword
For
immediately preceding the condition that you want to evalute. - A variable to use as a counter, and its initial value.
- The keyword
to
ordownto
immediately following the value of the counter. - The value at which the loop stops. This value can be a number, variable, or AMPscript function.
- The keyword
do
. - The code to execute in each loop.
- The keyword
next
to iterate the counter. If you used the keywordto
, the counter increases by one. If you useddownto
, the counter decreases by one.
These keywords aren’t case-sensitive; that is, FOR
, For
, and for
all function in the same way.
In their simplest form, For
loops execute code a pre-determined number of times. This example shows how to output a string of text a specific number of times, printing the number of iteration in each line.
The code outputs this text:
Several AMPscript functions can create or load data structures, such as data extensions. For example, when you provide it with a string of text, the BuildRowsetFromString()
function creates a data structure called a "rowset," which consists of one or more lines of tabular data.
This example shows how to parse the data in this rowset. It also demonstrates how you can close and resume AMPscript code blocks to suit your desired output. The comments in the example explain the purpose of each line.
The output of this example contains this text: