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
This month @nodexl announced that ServerlessSUMMIT & DevOpsSUMMIT own the world's top three most influential Kubernetes domains which are more influential than LinkedIn, Twitter, YouTube, Medium, Infoworld and Microsoft combined. NodeXL is a template for Microsoft® Excel® (2007, 2010, 2013 and 2016) on Windows (XP, Vista, 7, 8, 10) that lets you enter a network edge list into a workbook, click a button, see a network graph, and get a detailed summary report, all in the familiar environment of...
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...
IT professionals are also embracing the reality of Serverless architectures, which are critical to developing and operating real-time applications and services. Serverless is particularly important as enterprises of all sizes develop and deploy Internet of Things (IoT) initiatives. Serverless and Kubernetes are great examples of continuous, rapid pace of change in enterprise IT. They also raise a number of critical issues and questions about employee training, development processes, and opera...
AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.
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...
Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get tailored market studies; and more.
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...
As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility. As they do so, IT professionals are also embr...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...