House of Fusion
Search over 2,500 ColdFusion resources here
Home of the ColdFusion Community



8 For Loop (Loop)
8.1 A For loop will loop over a single operation or a block of operations contained within a set of curly braces ({}). The loop takes three arguments with each one being optional.
     Initial Value
     Condition to continue the loop
     Operation to take at end of iteration.
8.2 The initial value is usually set as a normal variable set. This will create a variable and give it an initial value. This is a global variable and care must be taken so it does not affect other variables or pieces of code.
8.3 The condition to continue the loop takes a standard comparison statement and checks if it is true. If it is, then the loop will go again. This check is done at the beginning of each loop iteration.
8.4 The operation to take at the end of the loop iteration is a standard assignment that will occur when a loop iteration is done but before the check to continue is performed.
8.5 A standard For loop may look like this. The variable i is set to an initial value of 1. At the end of the loop, i is incremented and then it is checked to see if it is less then or equal to 10. If it is, then the loop will run another iteration.
     For (i=1;i LTE 10; i=i+1)
          writeoutput(i&' ');
8.5.1 The LTE syntax is used due to the order of operation. If the operation was LT 10, then there would only be 9 iterations of the loop. If the EQ syntax was used, it would fail to run in the first place.
8.5.2 The syntax i=i+1 is used because ColdFusion does not have an incrementation syntax of i++. The IncrementValue() function could be used, but is both slow and is wasted here.
8.6 The variable set and the end operation do not have to be numeric in nature. This example shows how to set the initial value to a character, increment the character and check it to see if the loop should end. It will output the letters M, N and O seperated by a space.
     For (i="M";i NEQ "P"; i=Chr(Asc(i)+1))
          writeoutput(i&' ');
8.7 A For loop can also be used to loop through a query object. This For loop will loop through a query and output each row of column record to the browser. (This example is provided to show that you can use CFSCRIPT to loop over a query. If this is the only operation you are doing, a CFLOOP or a CFOUTPUT would be perfered).
     For (i=1;i LTE Queryname.Recordcount; i=i+1)
8.8 A For loop can also be used to loop through a list. This For loop will loop through a list and output each item.
     For (i=1;i LTE ListLen(list); i=i+1)
          writeoutput(ListGetAt(list, i)&'<BR>');

Designer, Developer and mobile workflow conference