Copying arrays

You can copy arrays of simple variables (numbers, strings, Boolean values, and date-time values) by assigning the original array to a new variable name. You do not have to use ArrayNew to create the array first. When you assign the existing array to a new variable, ColdFusion creates an array and copies the contents of the old array to the new array. The following example creates and populates a two-element array. It then copies the original array, changes one element of the copied array and dumps both arrays. As you can see, the original array is unchanged and the copy has a new second element.

<cfset myArray=ArrayNew(1)> 
<cfset myArray[1]="First Array Element"> 
<cfset myArray[2]="Second Array Element"> 
<cfset newArray=myArray> 
<cfset newArray[2]="New Array Element 2"> 
<cfdump var=#myArray#><br> 
<cfdump var=#newArray#>

If your array contains complex variables (structures, query objects, or external objects such as COM objects) assigning the original array to a new variable does not make a complete copy of the original array. The array structure is copied; however, the new array does not get its own copy of the complex data, only references to it. To demonstrate this behavior, run the following code:

Create an array that contains a structure.<br> 
<cfset myStruct=StructNew()> 
<cfset myStruct.key1="Structure key 1"> 
<cfset myStruct.key2="Structure key 2"> 
<cfset myArray=ArrayNew(1)> 
<cfset myArray[1]=myStruct> 
<cfset myArray[2]="Second array element"> 
<cfdump var=#myArray#><br> 
<br> 
Copy the array and dump it.<br> 
<cfset myNewArray=myArray> 
<cfdump var=#myNewArray#><br> 
<br> 
Change the values in the new array.<br> 
<cfset myNewArray[1].key1="New first array element"> 
<cfset myNewArray[2]="New second array element"> 
<br> 
Contents of the original array after the changes:<br> 
<cfdump var=#myArray#><br> 
Contents of the new array after the changes:<br> 
<cfdump var=#myNewArray#>

The change to the new array also changes the contents of the structure in the original array.

To make a complete copy of an array that contains complex variables, use the Duplicate function.