
87
DEVELOPING
COLDFUSION 9 APPLICATIONS
The CFML Programming Language
Las
t
upda
te
d 8/5/2010
Using implicitly created arrays
You can use implicitly created arrays directly in functions (including user-defined functions) and tags. For example,
the following code uses two implicit arrays, one in a ColdFusion function, the other in a user-defined function:
<cffunction name="sumarray">
<cfargument name="inarray" type="array">
<cfset result = 0>
<cfloop array="#inarray#" index="i" >
<cfset = i>
</cfloop>
<cfreturn result>
</cffunction>
<cfoutput>
Summed Implicit array [#ArrayToList([1,2,3,4,5,6])#]: #sumarray([1,2,3,4,5,6])#<br />
</cfoutput>
Adding elements to an array
You can add an element to an array by assigning the element a value or by using a ColdFusion function.
Adding an array element by assignment
You can add elements to an array by defining the value of an array element, as shown in the following
cfset
tag:
<cfset myarray[5]="Test Message">
If an element does not exist at the specified index, ColdFusion creates it. If an element exists at the specified index,
ColdFusion replaces it with the new value. To prevent existing data from being overwritten, use the
ArrayInsertAt
function, as described in the next section.
If elements with lower-number indexes do not exist, they remain undefined. Assign values to undefined array elements
before you can use them. For example, the following code creates an array and an element at index 4. It outputs the
contents of element 4, but generates an error when it tries to output the (nonexistent) element 3.
<cfset myarray=ArrayNew(1)>
<cfset myarray[4]=4>
<cfoutput>
myarray4: #myarray[4]#<br>
myarray3: #myarray[3]#<br>
</cfoutput>
<cfset biggestarray=ArrayNew(3)>
<cfset biggestarray[3][1][1]=biggerarray>
<cfset biggestarray[3][1][1][2][3][1]="This is complex">
Create a second 3D array. Make the [3][1][1] element of this
array a copy of the biggerarray array, and assign element
[3][1][1][2][3][1].
The resulting array is complex and asymmetric.
<cfset myarray[3]="Can you see me">
Assign a value to element [3] of myarray.
<cfdump var=#biggestarray#><br>
<cfdump var=#myarray#>
Use cfdump to view the structure of biggestarray and myarray.
Notice that the "Can you see me" entry appears in myarray, but
not in biggestarray, because biggestarray has a copy of the
original myarray values and the change to myarray does not
affect it.
Code
Description