User Guide

Populating Arrays with Data 121
Populating Arrays with Data
Array elements can store any values, including queries, structures, and other arrays.
You can use a number of functions to populate an array with data, including
ArraySet, ArrayAppend, ArrayInsertAt, and ArrayPrepend. These functions are
useful for adding data to an existing array.
In particular you should master the following basic techniques:
Populating an array with
ArraySet
Populating an array with cfloop
Populating an array from a query
Populating an array with ArraySet
You can use the ArraySet function to populate a 1D, or one dimension of a
multidimensional array, with some initial value such as an empty string or 0 (zero).
This can be useful if you need to create an array of a certain size, but do not need to
add data to it right away. One reason to do this is so that you can refer to all the array
indexes. If you refer to an array index that does not contain some value, such as an
empty string, you get an error.
The
ArraySet function has the following form:
ArraySet (arrayname, startrow, endrow, value)
This example initializes the array myarray, indexes 1 to 100, with an empty string.
ArraySet (myarray, 1, 100, "")
Populating an array with cfloop
A common and very efficient method for populating an array is by creating a looping
structure that adds data to an array based on some condition using
cfloop.
The following example uses a
cfloop tag and the MonthAsString function to
populate a simple 1D array with the names of the months. A second
cfloop outputs
data in the array to the browser.
<cfset months=arraynew(1)>
<cfloop index="loopcount" from=1 to=12>
<cfset months[loopcount]=MonthAsString(loopcount)>
</cfloop>
<cfloop index="loopcount" from=1 to=12>
<cfoutput>
#months[loopcount]#<br>
</cfoutput>
</cfloop>