You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Structures and Arrays Part 2

Similar but different beasts

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:


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">

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">
   #temp#: #application.Users[temp]#<Br>

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.
You can find a complete list of all structure functions and more details on all of them in your Macromedia documentation or in the livedocs at Click Here !.

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.

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.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.