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
<cfset myarray[5]="Test Message">
If an element does not exist at the specified index, ColdFusion creates it. If an element already
exists at the specified index, ColdFusion replaces it with the new value. To prevent existing data
from being overwritten, use the
If elements with lower-number indexes do not exist, they remain undefined. You must 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>
Adding an array element with a function
You can use the following array functions to add data to an array:
Function
ArrayAppend
ArrayPrepend
ArrayInsertAt
Because ColdFusion arrays are dynamic, if you add or delete an element from the array, any
higher-numbered index values all change. For example, the following code creates a two element
array and displays the array contents. It then uses
beginning of the array and displays the result. The data that was originally in indexes 1 and 2 is
now in indexes 2 and 3.
<!--- Create an array with three elements --->
<cfset myarray=ArrayNew(1)>
<cfset myarray[1]="Original First Element">
<cfset myarray[2]="Original Second Element">
<!--- Use cfdump to display the array structure --->
<cfdump var=#myarray#>
<br>
<!--- Add a new element at the beginning of the array --->
<cfscript>
ArrayPrepend(myarray, "New First Element");
</cfscript>
<!--- Use cfdump to display the new array structure --->
<cfdump var=#myarray#>
108
Chapter 5: Using Arrays and Structures
tag:
ArrayInsertAt
Description
Creates a new array element at the end of the array.
Creates a new array element at the beginning of the array.
Inserts an array element at the specified index position.
function, as described in the next section.
to insert a new element at the
ArrayPrepend
Need help?
Do you have a question about the COLDFUSION MX 61-DEVELOPING COLDFUSION MX and is the answer not in the manual?
Questions and answers