![]() ![]() ![]() |
To use arrays in ColdFusion, as in other languages, you need to first declare the array, specifying its dimension. Once it's declared, you can add array elements, which you can then reference by index.
As an example, say you declare a one-dimensional array called "firstname":
<CFSET firstname=ArrayNew(1)>
At first, the array firstname holds no data and is of an unspecified length. Now you want to add data to the array:
<CFSET firstname[1]="Coleman"> <CFSET firstname[2]="Charlie"> <CFSET firstname[3]="Dexter">
Once you've added these names to the array, it has a length of 3:
<CFSET temp=ArrayLen(firstname)> <!--- temp=3 --->
If you remove data from an index, the array resizes dynamically:
<CFSET temp=ArrayDeleteAt(firstname, 2)> <!--- "Charlie" has been removed from the array ---> <CFOUTPUT> The firstname array is #ArrayLen(firstname)# indexes in length </CFOUTPUT> <!--- Now the array has a length of 2, not 3 --->
The array now contains:
firstname[1]=Coleman firstname[2]=Dexter
You can add elements to an array by simply defining the value of an array element:
<CFSET myarray[1]=form.variable>
But you can also employ a number of array functions to add data to an array. You can use ArrayAppend to create a new array index at the end of the array. You can use ArrayPrepend to create a new array index at the beginning of the array. You can also use ArrayInsertAt to insert an array index and data. When you insert an array index with ArrayInsertAt, as with ArrayDeleteAt, all indexes to the right of the new index are recalculated to reflect the new index count.
For more information about these array functions, see the CFML Language Reference.
Because ColdFusion arrays are dynamic, be careful when referencing array indexes. If you add or delete an element from the middle of an array, subsequent index positions all change.
When an array index is deleted, index positions in the array are recalculated. For example, in a 1D array containing the months of the year, deleting index position [5] removes the entry for May. If you then want to delete the entry for November, you delete index position [10], not [11], since the index positions were recalculated after index position [5] was removed.
![]() ![]() ![]() |
AllaireDoc@allaire.com
Copyright © 1998, Allaire Corporation. All rights reserved.