Cold Fusion Tips-N-Tricks
Creating arrays of more than three dimensions

According to the CF Docs, you can only create an array of three dimensions max. So you can have a one dimensional array referenced as MyArray[a], a two dimensional array as MyArray[a][b], and a three dimensional array as MyArray[a][b][c].

But you could not create a four dimensional array as MyArray[a][b][c][d] because <CFSET MyArray=ArrayNew(4)> would generate an error.

However, the one really sweet feature about Cold Fusion is that you can store any type of variable inside another variable.  You can store a query or structure inside an array element.

For example:

<CFSET MyArray=ArrayNew(1)>
<CFSET MyArray[1]=StructNew()>
<CFSET MyArray[1].MyQuery=QueryNew("field1,field2")>


There - I just created a query that exists inside a structure that exists inside an array element.

Now the trick with creating an array of more than three dimensions is to create an array inside an array.

To give an example, you can create a 2D array with the following command:

<CFSET MyArray=ArrayNew(2)>
<CFSET MyArray[1][1]="A">


Using the nested array trick, you can do the same thing with:
<CFSET MyArray=ArrayNew(1)>
<CFSET MyArray[1]=ArrayNew(1)>
<CFSET MyArray[1][1]="A">


With this trick, we can create arrays of any number of dimensions.  In the below code, I'll create a 6D array:
<!--- Assign six dimensional loop --->
<CFLOOP index="d1" from="1" to="3">
  <CFSET MyArray[d1]=ArrayNew(1)>
  <CFLOOP index="d2" from="1" to="3">
    <CFSET MyArray[d1][d2]=ArrayNew(1)>
    <CFLOOP index="d3" from="1" to="3">
      <CFSET MyArray[d1][d2][d3]=ArrayNew(1)>
      <CFLOOP index="d4" from="1" to="3">
        <CFSET MyArray[d1][d2][d3][d4]=ArrayNew(1)>
        <CFLOOP index="d5" from="1" to="3">
          <CFSET MyArray[d1][d2][d3][d4][d5]=ArrayNew(1)>
          <CFLOOP index="d6" from="1" to="3">
            <CFSET MyArray[d1][d2][d3][d4][d5][d6]="#d1#,#d2#,#d3#,#d4#,#d5#,#d6#">
          </CFLOOP>
        </CFLOOP>
      </CFLOOP>
    </CFLOOP>
  </CFLOOP>
</CFLOOP>

<CFDUMP var="#MyArray#">


Return to the Cold Fusion Tips-N-Tricks topic list