• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Nested Loops

It is possible to nest loops in a fashion similar to the way we nested IF statements. This can be a very useful feature. Look at the following code to see an example of nested loops used to dynamically build an HTML table.

<!--- set the number of rows and columns ---> 
<CFSET Rows = 4> 
<CFSET Cols = 5> 
<!--- start the table outside the loop ---> 
<TABLE BORDER="1" CELLSPACING="0" CELLPADDING="1"> 
   <!--- start outer loop ---> 
   <CFLOOP INDEX="x" FROM="1" TO="#Rows#"> 
      <!--- start row code ---> 
      <TR> 
            <!--- start inner loop ---> 
            <CFLOOP INDEX="y" FROM="1" TO="#Cols#"> 
                  <!--- start code for columns ---> 
                  <TD> 
                        <CFOUTPUT>Row #x#, Col #y#</CFOUTPUT> 
                  </TD> 
            </CFLOOP> 
      <!--- finish row code ---> 
      </TR> 
   </CFLOOP> 
<!--- finish the table ---> 
</TABLE>

After setting the values for the rows and columns of our table, we start an outer loop that begins the code for a table row. After that is complete, we drop into an inner loop that creates the code for our table cells by looping over some <TD> code. When the correct number of <TD> cells has been created (in this case, 5), we complete the inner loop and jump back into the outer loop. The outer loop finishes off the code for that row with a closing </TD> tag and loops back to the top to start all over again. This continues until the specified number of rows has been created.

Figure 4.6. Nested loop output.


  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint