|By Jeffry Houser||
|May 11, 2004 12:00 AM EDT||
This is the first of a two-part column in which I'll teach you about structures and arrays, two of the complex data types in ColdFusion. To start, I'll introduce structures and arrays and then go into some details on how to make use of arrays in ColdFusion.
Next month I'll go into detail on structures and then compare and contrast the two. Along the way I'll provide plenty of examples for you to learn from. In short, both structures and arrays give you a way to group a lot of related pieces of data together.
Understanding Structures and Arrays
Structures and arrays are considered complex data types in ColdFusion. Simple data types by contrast are ones that contain a single piece of data, such as a number, string, or Boolean value. A complex data type can contain multiple pieces of data, usually related. All the pieces of data are referenced under a single variable name. Think of a complex variable as a variable that has other variables inside it.
You can access a single data element of an array (a variable inside the array) by using a number. This number is often called the "index" of the array. A single data element of a structure, by comparison, is accessed using a string. If you are familiar with other languages, you may have heard of a structure referred to as an associative array. That is because a string value is used to associate with the single data element. So arrays reference each of the values within themselves with a number (representing their position in the array), and structures reference each of their values by name.
Arrays are great for number crunching since many of the built-in array functions will perform math functions on a set of numbers. They also work well when processing multiple elements of data in a loop, but don't need immediate access to an individual element. An example of this is a shopping cart application. An array is an ideal way to store all the items in a shopping cart. When you add something to the cart, it does not matter where in the cart it ends up. When you go to check out, you are going to process all the items in the cart as a group, and not individually. You pick up an item from the cart, run it through the scanner, and move on to the next one. There is no reason to process one item before the other.
Structures are great when you are going to need to access data elements by name. An example of this is each item residing in your shopping cart. Although it doesn't matter in what order you process the items, when you get an individual item (a value in the array) you'll want easy and direct access to properties of the element such as the price, quantity, name, or UPC value.
ColdFusion does not place any limitations on the data that can be put into an array or structure. It can be simple variables, such as an integer or string; or even complex variables such as another array, structure, or component. In practice, many shopping cart applications use an array of structures to store the data.
One major difference between arrays and structures is that arrays have something called "dimension", but structures do not. Most often arrays have one dimension, which is akin to a list of items, similar to a single row in a spreadsheet. Our shopping cart is an example of a one-dimensional array. It contains a list of items, stored sequentially. This is an example of a one-dimensional array:
We can access the individual elements of the array using the name of the array, an open (square) bracket '[', the array index we want to access, and a close bracket, ']'. If we had created an array called MyArray, we could access the third element of the array like this:
Using the sample array above we would get the value candy bar.
Arrays can also have two dimensions, similar to a spreadsheet with multiple rows. One dimension specifies the row and another dimension specifies the column. Sometimes it's good to think of a two-dimensional array as an array inside an array. This is an example of a two-dimensional array.
In the two-dimensional array you must retrieve data elements using a dual index, specifying the value you want in the first and second dimension. Each index is specified using the square brackets, just as if you were referencing a single-dimension array. This is an example:
This retrieves the value at row 1, column 1 (carrots). If you want to retrieve row 1, column 2, you'll get beans. Row 2, column 1 will give you bread, and so on.
One way to think of two-dimensional arrays is as a one-dimensional array, where each data element of the array is another array. In the array above, if we were to retrieve the first element of the two-dimensional array, we'd receive this one-dimensional array:
Using ColdFusion's array creation functionality we can create arrays with up to three dimensions. If you think of 2D arrays like a spreadsheet, a 3D array would be like a cube. You can create arrays beyond three dimensions, but they become hard to conceptualize and are beyond the scope of this article. You can read more about them at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/arrayst8.htm.
Creating and Using Arrays
It's time to write some code. Our first step is to create an array. Simple variables, such as strings or numbers, don't require any sort of declaration before use, but arrays do. We can use the cfset tag in combination with the ArrayNew function to define the array (see this column in the February 2004 issue for more on CFSET). The function has one parameter, which defines the number of dimensions of the array. As previously discussed, we can enter a value of 1, 2, or 3. This will create a one-dimensional array:
<cfset MyArray = ArrayNew(1)>
Now we have an empty one-dimensional array. The next step is to add some elements to it. We can access the individual elements of the array using the name of the array, MyArray, an open (square) bracket '[', the array index we want to access, and a close bracket, ']'. This will come across more clearly with an example. We can set an array value like this:
<cfset MyArray = "Carrots">
The value can be output on a page like this:
This is fine when ColdFusion is accessing a single dimensional array as in our current example, but I wanted to make sure you knew how to apply this to multiple dimensions. Just add on another set of brackets and the number for the second index. To access the first value of the first array, you can use this:
To access array values from arrays with other dimensions, you can just tack on additional indexes until you reach your value. A three-dimensional array can be accessed like this:
In a multidimensional array, as you add a new index to a dimension, it is immediately created as an array. Back to our one-dimensional array example, this code will finish creating our example array from above:
<cfset MyArray = "Bread">
<cfset MyArray = "Candy Bar">
<cfset MyArray = "Milk">
It's worth noting here how ColdFusion handles arrays internally. They are sized automatically as you add and remove elements. When you create an array with ArrayNew, there are no elements in it yet. As you start to add elements, ColdFusion will grow the array. When you remove elements ColdFusion will automatically shrink the array. This helps save memory because you aren't storing empty data references. As you add and remove elements, the index of existing elements in an array may change. Do not use arrays in situations where this will cause a problem.
Now you have a variable, MyArray, which refers to a one-dimensional array. The array has four elements. As discussed before, one of the primary reasons to use an array is to perform processing on all elements. The simplest form of processing is to output something. We can loop over an array using the cfloop tag and an index loop. I'll probably dedicate a future column to the cfloop tag; however you can read about index loops at http://livedocs.macromedia.com/coldfusion/6.1/ htmldocs/tags-p77.htm#wp1101087. Index loops are used to loop a specific number of iterations. In this case we want to loop from 1 to the length of the array.
You'll need three attributes to the cfloop tag to create an index loop for looping over all elements of the array. The first is the "index". The index specifies the name of a variable that will contain the current loop iteration. The "from" attribute specifies the first value of the index (which is "1" to loop from the first element of an array). The "to" attribute specifies the last value of the index before looping terminates. Unless otherwise specified (with the "step" attribute) the increment each time through the loop will be +1.
For the "index" we can use any valid variable name, such as "ArrayIndex". To start processing at the first index of the array, set the "from" attribute to "1". You'll need to know the size of the array to loop over all of the elements. ColdFusion provides a function, ArrayLen. It accepts one attribute, the array you want the size of. In multidimensional arrays, it will only specify the size of the first dimension. This is the code to loop through the array and display its values:
<cfloop index="ArrayIndex" from="1" to="#ArrayLen(MyArray)#"> <cfoutput>#MyArray[ArrayIndex]#</cfoutput>
If you put all the code segments from this section into a single template and load it in your browser you'll see each element of the array displayed to the browser.
The previous section introduced you to creating arrays with the ArrayNew function and finding the length of an array with the ArrayLen function. There are many other functions that can be used in conjunction with arrays. Here are a few of the more common ones:
- IsArray: The IsArray function will check whether or not a given value is a valid array. It accepts two parameters - the array and the dimension.
- ArrayIsEmpty: The ArrayIsEmpty function accepts an array as a parameter and returns true if the array does not yet have any elements in it. It returns false if it does.
- ArrayAppend: The ArrayAppend function is used to add an element to the end of the array. Its parameters are the array and the value you want to add.
- ArrayPrepend: The ArrayAppend function is used to add an element to the beginning of the array. Its parameters are the array and the value you want to add.
- ArrayInsertAt: The ArrayInsertAt function allows you to add an element to any point in a given array that you specify. Its arguments are the array, the position in which you want to insert your value, and the value that you want to add.
- ArrayDeleteAt: The ArrayDeleteAt function allows you to remove an element at any specified point in the array. Its arguments are the array, the position you want to delete your value from, and the value that you want to add.
- ArraySum: The ArraySum function returns the sum of all elements from the array. It accepts a single argument, the array.
- ArrayAvg: The ArrayAvg function will return the average of all elements in the array. Its single parameter is the array.
- ArrayMax: The ArrayMax function will return the largest value in the array. It accepts a single parameter - the array. It will work only on arrays that contain numeric data.
- ArrayMin: The ArrayMin function returns the smallest value in the array. Its sole parameter is the array. It will work only on arrays that contain numeric data.
- ArraySort: The ArraySort function will sort the elements in an array. It returns a true value if the array was sorted, false otherwise. Its parameters are the array, the sort type (numeric, text, or textnocase), and the sort order (asc or desc).
- ArrayClear: The ArrayClear variable will delete all data in an array.
That's all there is to say about arrays (in the length given in this article). You can read more about arrays in the Macromedia documentation at http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/ arrayst2.htm#wp1096146. Because of the built-in functions, arrays are often good for processing numbers and spreadsheet-related functions. Next month I'll talk about structures, the other complex variable.
|Jillian Carroll 05/12/04 07:08:19 PM EDT|
Thank you! I''ve been looking for -exactly- this primer to pass around to my colleagues.
- Where Are RIA Technologies Headed in 2008?
- The Next Programming Models, RIAs and Composite Applications
- AJAX World RIA Conference & Expo Kicks Off in New York City
- Constructing an Application with Flash Forms from the Ground Up
- Building a Zip Code Proximity Search with ColdFusion
- Personal Branding Checklist
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Has the Technology Bounceback Begun?
- Adobe Flex 2: Advanced DataGrid
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers
- Web Services Using ColdFusion and Apache CXF
- Passing Parameters to Flex That Works