Adobe COLDFUSION 9 Manual page 94

Developing applications
Hide thumbs Also See for COLDFUSION 9:
Table of Contents

Advertisement

DEVELOPING COLDFUSION 9 APPLICATIONS
The CFML Programming Language
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
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
Populating arrays with data
Array elements can store any values, including queries, structures, and other arrays. You can use assignment
statements to populate an array. You can also use several of functions to populate an array with data, including
,
,
ArraySet
ArrayAppend
ArrayInsertAt
existing array.
In particular, consider using the following techniques:
• Populating an array with the
, and
ArrayPrepend
function
ArraySet
Last updated 8/5/2010
to create the array first. When you assign the
ArrayNew
Duplicate
. These functions are useful for adding data to an
function.
89

Advertisement

Table of Contents
loading

Table of Contents