The ability to directly use an
arrayobject withcfloopwas added in ColdFusion 8.
Consider this array;
<cfset aFoo = [
"one"
, "two"
, "three"
, "four"
] />
Using the attribute index by itself.
| Attribute | Required | Default | Description |
|---|---|---|---|
| array | true | An array object. The variable must be evaluated (wrapped with ##) | |
| index | true | The current element of the array. |
<cfoutput>
<cfloop array="#aFoo#" index="x">
<li>#x#</li>
</cfloop>
</cfoutput>
This will also have a line break between each line of HTML.
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
The attribute
itemchanges the behavior ofcfloopas of Coldfusion 2016.
Using the attribute item instead of or in addition to index.
| Attribute | Required | Default | Description |
|---|---|---|---|
| array | true | An array object. The variable must be evaluated (wrapped with ##) | |
| item | true | The current element of the array. | |
| index | false | The current index of the array. |
<cfoutput>
<cfloop array="#aFoo#" item="x" index="y">
<li>#x# | #y#</li>
</cfloop>
</cfoutput>
This will also have a line break between each line of HTML.
<li>one | 1</li>
<li>two | 2</li>
<li>three | 3</li>
<li>four | 4</li>
<cfscript>
for (i = 1; x LTE arrayLen(aFoo); i = i + 1) {
writeOutput("<li>" & aFoo[i] & "</li>");
}
</cfscript>
<cfscript>
for (i = 1; i <= arrayLen(aFoo); i = i++) {
writeOutput("<li>" & aFoo[i] & "</li>");
}
</cfscript>
With the
FOR INsyntax, x is the current array element, not the array index.
<cfscript>
for (x in aFoo) {
writeOutput("<li>" & x & "</li>");
}
</cfscript>
The cfscript function
cfloophas no support forarray.
Notice that the cfscript output is all on one line.
<li>one</li><li>two</li><li>three</li><li>four</li>