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>

Adding an array element with a function

You can use the following array functions to add data to an array:

Function

Description

ArrayAppend

Creates an array element at the end of the array.

ArrayPrepend

Creates an array element at the beginning of the array.

ArrayInsertAt

Inserts an array element at the specified index position.

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 ArrayPrepend to insert a new element at the 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#>

For more information about these array functions, see the CFML Reference.