coldfusion Array


Example

The ability to directly use an array object with cfloop was added in ColdFusion 8.

Consider this array;

<cfset aFoo = [
    "one"
    , "two"
    , "three"
    , "four"
] />

Tag syntax

ColdFusion 8 through current

Using the attribute index by itself.

Parameters

AttributeRequiredDefaultDescription
arraytrueAn array object. The variable must be evaluated (wrapped with ##)
indextrueThe current element of the array.
<cfoutput>
    <cfloop array="#aFoo#" index="x">
        <li>#x#</li>
    </cfloop>
</cfoutput>

Generated HTML

This will also have a line break between each line of HTML.

<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>

ColdFusion 2016 through current

The attribute item changes the behavior of cfloop as of Coldfusion 2016.

Using the attribute item instead of or in addition to index.

Parameters

AttributeRequiredDefaultDescription
arraytrueAn array object. The variable must be evaluated (wrapped with ##)
itemtrueThe current element of the array.
indexfalseThe current index of the array.
<cfoutput>
    <cfloop array="#aFoo#" item="x" index="y">
        <li>#x# | #y#</li>
    </cfloop>
</cfoutput>

Generated HTML

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

Previous to ColdFusion 8

<cfscript>
for (i = 1; x LTE arrayLen(aFoo); i = i + 1) {
    writeOutput("<li>" & aFoo[i] & "</li>");
}
</cfscript>

ColdFusion 8 through current

<cfscript>
for (i = 1; i <= arrayLen(aFoo); i = i++) {
    writeOutput("<li>" & aFoo[i] & "</li>");
}
</cfscript>

ColdFusion 9 through current

With the FOR IN syntax, x is the current array element, not the array index.

<cfscript>
for (x in aFoo) {
    writeOutput("<li>" & x & "</li>");
}
</cfscript>

ColdFusion 11 through current

The cfscript function cfloop has no support for array.

Generated HTML

Notice that the cfscript output is all on one line.

<li>one</li><li>two</li><li>three</li><li>four</li>