| By Jeffry Houser | Article Rating: |
|
| June 22, 2004 12:00 AM EDT | Reads: |
24,816 |
Arrays and structures are complex data types in ColdFusion. It is important to have an understanding not only of how to use them, but also of when it is best to use one over the other.
This is the second of a two-part series in which I teach you about structures and arrays. In Part 1 (ColdFusion Developer's Journal, Vol. 6, issue 5), I introduced structures and arrays, and investigated arrays in more detail. In this article I'll go into greater detail on structures and then compare and contrast the two complex data types.
Reviewing Structures and Arrays
A simple data type is one that contains a single value. Complex data types can be seen as a group of multiple values, all stored in a single variable. Arrays and structures are the two most common complex data types in ColdFusion. As you may remember from Part 1, you can access an individual array element by using a number, called an index. Values in a structure can be accessed in a similar manner, except that the index is a string instead of a number.
If you are familiar with other programming languages, you may have heard of something called associative arrays. Structures in ColdFusion are similar to associative arrays in other languages. The index is a name that is associated with the value you place in it. The elements that make up a structure are known as key/value pairs. The key is another name for the index and, as I said, is used to access the value. The value portion of a structure can be any valid value in ColdFusion, including integers, strings, arrays, objects, or even other structures. It might help you to conceptualize a structure as a two-column spreadsheet, with the key being one column and the value being the second column.
Structures are great for storing related elements. In one of my current projects, we are using a structure to store directory information about the project, such as the location of include files, image files, custom tags, and ColdFusion Components. The elements of this structure might look like Table 1.
Throughout our application, it is easy to access the directory information we need just by grabbing the proper values out of the structure.
Creating and Using Structures
With a general understanding of what structures are, the next logical step is to show you how to create structures in ColdFusion. With arrays we used a function called ArrayNew to create the array. With structures we use a function called StructNew. This is the syntax:
<cfset MyStruct = StructNew()>
Unlike ArrayNew(), the StructNew function does not accept any arguments.
Creating a structure is easy. The next step is to learn how to add elements to the structure. To understand that, you must first know how to access elements of a structure. There are two methods for accessing elements of a structure: dot notation and associative array notation (also called square-bracket notation). Dot notation takes this form:
Structure.Key
It starts with the name of the structure, following that is a period, and after the period comes the key. I've also heard dot notation referred to as object property notation because the syntax is very similar to the way you would access properties of an object. This is the most common syntax used for accessing structure keys because it is very similar to the way you may access variables in a variable scope or columns in a query result set.
To add an element into a structure using dot notation we can use the cfset tag, like this:
<cfset MyStruct.Includes = "inc/">
The line of code starts with the cfset tag. It is followed by a space and then the name of the structure. The structure is followed by a dot and then the name of the key. After that we have an equals sign and the value. This line of code creates the key, Includes, inside the structure, MyStruct, and gives it a string value of inc/.
Associative array notation is another way to access elements of a structure. You may remember how we accessed values in an array in Part 1. We used the name of the array, then an open square bracket "[", followed by the index number, and finished off with a close square bracket "]". To access a structure's value using associative array notation, we use the same approach. The only difference is that instead of placing a number between the brackets, we use a string. Here is an example:
<cfset MyStruct["Images"] = "Images/">
This line of code creates the key, Images, inside the structure, MyStruct, and gives it the string value of Images/.
There are quite a few benefits to using the associative array notation over the dot notation. First, your key name can have spaces or special characters. Second, you don't have to know the name of the key when setting or accessing it. The key name can be a variable or an unknown value. Dynamically named structures can be great if you don't know what you are going to be storing beforehand. A third benefit of this method is that the keys will retain their case. Using the object property notation, all keys will be converted to uppercase. Next, we'll look at an example of using array notation to dynamically name a structure.
Dynamically Named Structures
Suppose you want to keep track of how many active users are on your site. For simplicity's sake, we will assume that this is a private site and users cannot get to it without first logging in. We can use a structure in the application scope to keep track of the username and the date when they log in. We can use the username as the key and the login time stamp as the value.
The following code snippet is a simple login form:
<form action="loginip.cfm" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
The form accepts two values, a username and a password, and has a submit button. The code on the form-processing page (loginip.cfm) that will store the username and time stamp in the application scope looks like this:
<cfset application.Users[form.username] = Now()>
Under normal circumstances you'll have more code to process the login, but this line is fine for demonstration purposes. The line of code adds a new element to the users structure in the application scope. The name is the value of username, which the user entered in the login form. The value is gotten by using one of ColdFusion's date functions, now(), which returns the server's current datetime stamp. Note that before using the application scope you'll have to set it up with the cfapplication tag. Although it is beyond the scope of this article, more information on using the cfapplication tag can be found at Click Here !.
Because the "form.username" text is not inside quotes, ColdFusion recognizes it as a variable and uses the value rather than a string literal. The line of code shown earlier could also be rewritten like this:
<cfset application.Users["#form.username#"] = Now()>
It would work just as well. ColdFusion recognizes the pound signs inside the string and knows to evaluate the string. I prefer the first method because it is easier to code and easier to read. However, the second method is the one of choice if you are mixing a string literal with a variable's value to form the variable name, like this:
<cfset application.Users["Users#form.username#"] = Now()>
To help with the processing of structures, we can use the cfloop tag to loop over structures. The cfloop tag accepts two attributes for looping over a structure, the collection attribute and the item attribute. The collection attribute accepts the structure value. The item attribute specifies the name of a temporary variable. The variable can be used inside the loop to access the specific element of the structure. The following code snippet is an example of how to loop over the users structure:
<cfloop collection="#application.users#" item="Temp">
<cfoutput>
#temp#: #application.Users[temp]#<Br>
</cfoutput>
</cfloop>
The snippet starts with the cfloop open tag. For the collection attribute, we specify the name of our structure, application.users. You'll notice that we specify the pound signs around it. The item attribute we specify is temp, a temporary variable. We are going to display each key and its value inside the loop. First we display the key, which is stored in the variable temp. We use the dynamic addressing and the associative array notation to get the value of the structure.
It is worth nothing that when you create a structure in ColdFusion MX, you do not have to use the StructNew function. Using a cfset tag with either type of notation will create a structure on the fly. ColdFusion will explicitly create a structure without using the StructNew function. I generally avoid this practice for two reasons. First, using StructNew to explicitly define the structure will make the code more readable when it has to be revisited in six months. The second reason is backward compatibility. Versions earlier than ColdFusion 5 do not support the creation of structures without the use of the StructNew function. However, pre-CFMX versions do support the use of periods inside a variable name, so your code will work. The difference between a structure and a variable name with a period in it is an important distinction.
Structure Functions
ColdFusion provides a lot of built-in functions for structures. The following is a partial list:
- StructInsert: A function to insert an item into a structure. Its attributes are the structure, the key, the value, and a Boolean value that specifies whether or not to allow existing values to be overwritten. It returns true on the successful addition of the key to the structure.
- StructFind: The StructFind function determines whether the specified key is located in the structure. It returns the value associated with the specified key. Its arguments are the structure, and the key to look for.
- StructFindKey: StructFindKey is a function that will search through a structure to find the specified key. This is a recursive search, so if you have nested structures, all of the structures will be searched. Its attributes are the structure to search, the value for which to search keys for, and the scope of the search. The scope of the search is either "one" or "all". An array is returned that contains all the found values.
- StructFindValue: The StructFindValue function is similar to the StructFindKey function. It searches recursively through a structure for values that match the specified values. Its values are the structure to search, the value to search for, and the scope (one or all). It returns an array that contains all structures that have matching values.
- StructClear: The StructClear function will remove all data from a structure. It accepts one argument, the structure you want to delete. It returns a Boolean value specifying whether or not the operation was successful.
- StructDelete: The StructDelete function will remove a single key value from a structure. Its arguments are the structure, the key you want to delete, and a Boolean value that specifies what to do if the key exists. If the Boolean value is set to true, then true is returned if the key exists, and false is returned if it does not. If set to false, then true is returned regardless of whether or not the key exists.
- IsStruct: The IsStruct function will check to see whether or not a variable is a valid structure. It accepts one argument, which is the structure you want to check.
- StructIsEmpty: The StructIsEmpty function will check to see whether or not the specified structure has any keys. If it does not, then true is returned; otherwise false is returned. Its single argument is the structure you want to check.
- StructCount: The StructCount function will return the number of keys in a structure. Its single argument is the structure.
- StructSort: The StructSort function will return a sorted array of the structure's keys. It does not actually change the structure's value in memory. Its arguments are the structure you want to sort, the sort type (numeric, text, or textnocase), the sort order (asc for ascending or desc for descending), and the path to subelement. The path to subelement is for advanced sorting and is beyond the scope of this article.
Conclusion
Arrays and structures are similar but different beasts. You should now have a good understanding of each. Both contain multiple values underneath a single variable name. Both use an index to access an individual value, but the index is numeric for arrays and a text value for structures. Arrays are best for number crunching, table-like data, and data sorting. Structures, by their nature, cannot be sorted by value - only by key name. They are best for related data, where order is not important and direct access to an individual element is important. Many of ColdFusion's variable scopes can be accessed as structures.
Published June 22, 2004 Reads 24,816
Copyright © 2004 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Jeffry Houser
Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.
- Oracle To Keynote Cloud Computing Expo
- Contrary Opinion: Why Silverlight is Good for Adobe
- Analytics for Adobe Air Applications
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Eval JavaScript in a Global Context
- Fig Leaf Software to Exhibit at Government IT Conference & Expo
- Is Microsoft as Free as Open Source?
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- The Planet Named “Bronze Sponsor” of Cloud Computing Expo
- Adobe Reader Sued
- AJAX World RIA Conference & Expo Kicks Off in New York City
- Adobe Enters Cloud Computing with LiveCycle
- Oracle To Keynote Cloud Computing Expo
- Social Media Terrorists
- Adobe Flash Media Server on iPhone
- Contrary Opinion: Why Silverlight is Good for Adobe
- Adobe Flash Based GetJar Surpasses a Half Billion Downloads
- Adobe ColdFusion 9 and ColdFusion Builder Public Betas Now Available
- Adobe Tries Commercializing Its Online Software
- Adobe Open Sources Flash Initiatives
- The Next Programming Models, RIAs and Composite Applications
- Where Are RIA Technologies Headed in 2008?
- Constructing an Application with Flash Forms from the Ground Up
- AJAX World RIA Conference & Expo Kicks Off in New York City
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Personal Branding Checklist
- Adobe Flex 2: Advanced DataGrid
- Has the Technology Bounceback Begun?
- Building a Zip Code Proximity Search with ColdFusion
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers



































