CFLOOP inside of a CFLOOP

I ran into a problem today and it turned out to be a simple naming conflict.

I had a loop that was looping through a session variable. I had named the index "i", which is my default loop index name. Inside the loop was a structDelete command which wasn't working.

<cfset maxValue = StructCount(session.formVars)>
<cfloop from="1" to="#maxValue#" index="i">
   <cfinclude template="act_ProcessFormVars.cfm">

   <cfset temp = structDelete(session.formVars,i)>
</cfloop>

After a bit of looking, I dug into the included file "act_ProcessFormVars.cfm" and found that there was a loop within it, that also used "i" for an index. This was causing a conflict and causing the variable "i" to be overwritten during each iteration of the loop. "i" would literally become the last value plus one of the inside loop at the time for structDelete to execute.

Here's an example:

<cfoutput>
<cfloop from="1" to="3" index="i">
   first: #i#<br>
   <cfloop from="1" to="3" index="i">
   &nbsp;&nbsp;&nbsp;&nbsp;inner:#i#<br>
   </cfloop>
   last: #i#<br><br>
</cfloop>
</cfoutput>

"i" in the above loop would become:

first: 1
    inner:1
    inner:2
    inner:3
last: 4

first: 2
    inner:1
    inner:2
    inner:3
last: 4

first: 3
    inner:1
    inner:2
    inner:3
last: 4

The solution is to simply rename one of the two loop's indexing names ("i" to "z"), and there won't be any conflicts!

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.