Using for loops

The for loop has the following format:

for (initial-expression; test-expression; final-expression) statement

The initial-expression and final-expression can be one of the following:

The test-expression can be one of the following:

Note: The test expression is re-evaluated before each repeat of the loop. If code inside the loop changes any part of the test expression, it can affect the number of iterations in the loop.

The statement can be a single semicolon terminated statement or a statement block in curly braces.

When ColdFusion executes a for loop, it does the following:

  1. Evaluates the initial expression.
  2. Evaluates the test-expression.
  3. If the test-expression is False, exits the loop and processing continues following the statement.

    If the test-expression is True:

  4. Executes the statement (or statement block).
  5. Evaluates the final-expression.
  6. Returns to Step 2.

For loops are most commonly used for processing in which an index variable is incremented each time through the loop, but it is not limited to this use.

The following simple for loop sets each element in a 10-element array with its index number.

for(index=1;
   index LT 10;
   index = index + 1)
   a[index]=index;

The following, more complex, example demonstrates two features:

<cfscript>
strings=ArrayNew(1);
ArraySet(strings, 1, 10, "lock");
strings[5]="key";
indx=0;
for( ; ; ) {
   indx=indx+1;
   if(Find("key",strings[indx],1)) {
      WriteOutput("Found key at " & indx & ".<br>");
      break;
      }
   else if (indx IS ArrayLen(strings)) {
      WriteOutput("Exited at " & indx & ".<br>");
      break;
      }
}
</cfscript>

This example shows one important issue that you must remember when creating loops: you must always ensure that the loop ends. If this example lacked the else if statement, and there was no "key" in the array, ColdFusion would loop forever or until a system error occurred; you would have to stop the server to end the loop.

The example also shows two issues with index arithmetic: in this form of loop you must make sure to initialize the index, and you must keep track of where the index is incremented. In this case, because the index is incremented at the top of the loop, you must initialize it to 0 so it becomes 1 in the first loop.


View comments in LiveDocs