Skip to main content
March 28, 2012
Question

When looping over an array, has 'index' always been the content of that element?

  • March 28, 2012
  • 2 replies
  • 1806 views

I have just written a cfloop with array="ArrMyArray" index="i" as the attributues for the first time in a long time. In the loop, #i# actually refers to the content of the current array element, which seems wrong. Surely #i# should be the index/counter? If I want a counter, do I have to make one manually? We upgraded from CF7 to CF9 about a year ago, surely this isn't different in those versions? As far as I remember, when a cfloop has an index attribute, it is basically asking you what var name you want for the counter which holds the number of the current loop iteration?

Thanks to anyone who can shed any light on this.

T

This topic has been closed for replies.

2 replies

Legend
March 28, 2012

I agree with Dan, looping through arrays is consistent with looping through lists. For any hard core traditionalists, or more precisely, hard code minimalists out there, you should only be using cfloop as an "indexloop" with the index, from, and to parameters. <cfloop index="i" from="1" to="#arrayLen(a)#">... would be the "non-flawed" version of a loop -- why would you use anything else if minimal is your cup of tea? Myself, I like having the option of looping through lists and arrays just how it is and always having the traditional indexloop option available for times when I need the counter.

Owainnorth
Inspiring
March 28, 2012

I don't think anyone's disagreeing with the different methods, just that the word "index" is a reserved word which means the integer position of a value within a collection, and so should not be used to point to a value.

This is fine:

for ( i=1; i<= arrayLen(a); i++ ) {

a

}

This is also fine:

foreach ( string str in a ) {

  str ;

}

But using what is essentially foreach loop with the word "index" is just wrong, the entire point of a foreach loop is that there's no index required.

Inspiring
March 28, 2012

Looping over arrays like that was only introduced into CF in CF8, so you would not have had that code in your CFMX7 code.

The implementation is flawed, as you point out: the index should be the index, not the value.  This was pointed out to Adobe but they have chosen to ignore it.

--

Adam

Owainnorth
Inspiring
March 28, 2012

Just tested it in 8.0.1 and agree it's wrong. The "item" attribute I'd expect to be the value, but not index="".