Using Arrays


Arrays are easy to use, but like all complex data, they must be created and initialized before they can be accessed. The array function ArrayNew() creates an array and takes one required argument. After you create the array, you must initialize it.

Creating Arrays

The ArrayNew() function creates an array and specifies the number of dimensions the array can hold. Passing an argument of 1 to ArrayNew(), as shown in the following example, creates a one-dimensional array. Multidimensional arrays will be discussed later in this chapter. After you create an array, you can access it by using functions or setting values directly.

 <!--- Create the grocery array ---> <cfset groceries = ArrayNew(1)> 

Populating Arrays

You can populate an array in a number of ways. The most specific way is to reference the index directly:

 <!--- Grocery list ---> <cfset groceries = ArrayNew(1)> <cfset groceries[1] = "Bread"> <cfset groceries[2] = "Cheese"> 

TIP

Array indexes may consist of any ColdFusion expression. For instance, you can reference an element at index [Q+1] by using groceries[Q+1]. To append a value to an array, you could use groceries[ArrayLen(groceries)+1].


An explicit reference to the array index works for simple initialization. To programmatically and dynamically populate an array, use the ArrayAppend() or ArrayPrepend() functions, which place values at the end or beginning of the array, respectively. Note that these functions, like most array functions, return TRUE in the variable to the left of the equals sign but perform their task against the array referenced in the array function.

 <cfset groceries = ArrayNew(1)> <cfset tmp = ArrayAppend(groceries,"Bread")> 

NOTE

Because it is not necessary to actually save any value returned by ArrayAppend(), the following code also would work:


 <cfset ArrayAppend(groceries,"Bread")> 

Accessing Array Values

Array values (or members) are accessed by an index that is specified within square brackets. The first value in an array could be accessed like this:

 groceries[1] 

To display the first grocery item, you could do the following:

 <cfoutput>#groceries[1]#</cfoutput> 

Printing all values in the array requires that you use the ArrayLen() function to determine the array length. The loop is a standard <cfloop> that uses the attributes from, to, and index. Because ArrayLen() returns the highest index in the array, this combination renders each value for every index:

 <ul> <cfloop from="1" to="#ArrayLen(groceries)#" index="i">  <li><cfoutput>#groceries[i]#</cfoutput></li> </cfloop> </UL> 

CAUTION

Although most programming languages start arrays at position 0, ColdFusion begins at array position 1. Attempting to loop, set, or read from position 0 throws an error.


You may not display arrays directly (as in <cfoutput>#groceries#</cfoutput>) because this throws an error. However, arrays may be passed to functions or tags if needed.

Converting Between Arrays and Lists

Because HTML forms and URL variables frequently pass lists to the Web server, being able to switch back and forth between complex data (arrays) and simple data (lists) is handy. The functions ArrayToList() and ListToArray() achieve these goals.

These functions are equally useful when you're working with SQL statements. For example, to use an array to populate a SQL IN clause (which expects a list), you could use ArrayToList().

Empty Array Indexes

An array may have a missing index, as in this code snippet:

 <!--- Grocery list ---> <cfset groceries = ArrayNew(1)> <cfset groceries[1] = "Bread"> <cfset groceries[2] = "Cheese"> <cfset groceries[4] = "Eggs"> <ul> <cfloop from="1" to="#ArrayLen(groceries)#" index="i">  <li><cfoutput>#groceries[i]#</cfoutput></LI> </cfloop> </ul> 

In this example, <cfloop> would attempt to loop from 1 to 4, but the <cfoutput> would fail on iteration 3 because #groceries[3]# is not a valid array index.

Obviously, if the array had been built dynamically (rather than by using explicit indexes), this would not have been a problem. But when indexes are explicitly created, use the ArraySet() function to initialize the indexes with values (even if the value is "").

Arrays and Memory

In ColdFusion, as with any server-side scripting language, performance is always a consideration. In most languagesJava, for examplearrays must be given a certain size before they are populated. ColdFusion does not require that a size be given because the array is dynamically resized. As data is placed into the array, ColdFusion appropriates memory along the way. Although this makes ColdFusion arrays very easy to use, this highly dynamic behavior can have performance implications.

For large arrays, it is recommended that the array be sized ahead of time so as to pre-allocate the memory that will be needed. That can be done using this ArrayResize() function:

 <cfset ArrayResize(groceries, 500)> 

TIP

The ColdFusion documentation recommends that an array be resized if it is likely to hold more than 500 indexes.


A resized array actually has multiple empty values in it. This means that a resized array should be initialized with ArraySet() if looping is likely to occur:

 <!--- Init list ---> <cfset groceries = ArrayNew(1)> <cfset ArrayResize(groceries, 500)> <cfset ArraySet(groceries, 1, 500, "")> 

Compressing Arrays

The solution for getting rid of empty values within an array is to compress the array by using the ArrayDeleteAt() function. This function not only deletes any value within a given index, but also compresses the array so that its length decrements by one. Compressing an array is a good practice to avoid some of the problems with empty values.

However, when you delete members from an array, keep in mind that indexes will change; thus no assumptions should be made about the array length or the specific index location.

Array Calculations

ColdFusion provides functions that may be used to sum array values; find minimums, maximums, and averages; and even sort values.

For example, you can sort arrays by using the ArraySort() function; one of the ollowing three sort types must be specified:

  • numeric should be used for arrays containing only numbers (and should never be used if any elements are not numeric).

  • text performs case-sensitive alphabetical sorting (A before a, 1 before 10, 2 after 1 but before 20, and numbers before letters).

  • textnocase performs an alphabetical sort that is not case sensitive.

An optional sort order may also be specified; the default is ASC (ascending), and the alternative is DESC (descending).

The following code snippet sorts the grocery list before displaying it:

 <!--- Grocery list ---> <cfset groceries = ArrayNew(1)> <cfset groceries[1] = "Bread"> <cfset groceries[2] = "Cheese"> <cfset groceries[3] = "Milk"> <cfset groceries[4] = "Eggs"> <!--- Sort list ---> <cfset ArraySort(groceries, "textnocase")> <ul> <cfloop from="1" to="#ArrayLen(groceries)#" index="i">  <li><cfoutput>#groceries[i]#</cfoutput></li> </cfloop> </ul> 

NOTE

These functions may only be used on single-dimensional arrays and not on multidimensional arrays (which will be explained next).




Macromedia ColdFusion MX 7 Certified Developer Study Guide
Macromedia ColdFusion MX 7 Certified Developer Study Guide
ISBN: 0321330110
EAN: 2147483647
Year: 2004
Pages: 389
Authors: Ben Forta

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net