User Guide

Table Of Contents
Basic array techniques 103
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 CFML Reference.
Deleting elements from an array
Use the
ArrayDeleteAt function to delete data from the array at a particular index, instead of
setting the data value to zero or an empty string. If you remove data from an array, the array
resizes dynamically, as the following example shows:
<!--- Create an array with three elements --->
<cfset firstname=ArrayNew(1)>
<cfset firstname[1]="Robert">
<cfset firstname[2]="Wanda">
<cfset firstname[3]="Jane">
<!--- Delete the second element from the array --->
<cfset temp=ArrayDeleteAt(firstname, 2)>
<!--- Display the array length (2) and its two entries,
which are now "Robert" and "Jane" --->
<cfoutput>
The array now has #ArrayLen(firstname)# indexes<br>
The first entry is #firstname[1]#<br>
The second entry is #firstname[2]#<br>
</cfoutput>
The ArrayDeleteAt function removed the original second element and resized the array so that
it has two entries, with the second element now being the original third element.