Welcome!

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 1

Use arrays for processing numbers and spreadsheet-related functions

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.

Array Dimensions
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:

Index Data
1 Carrots
2 Bread
3 Candy Bar
4 Milk

If you were to access the first element, it would be carrots. The second would be bread. The third would be a candy bar and the fourth, milk. For those who are knowledgeable about arrays in other languages, such as JavaScript, ColdFusion arrays start with an index of 1, not an index of 0.

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:

MyArray[3]

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.

Index 1 2
1 Carrots Beans
2 Bread Flour
3 Candy Bar Butter
4 Milk Salt

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:

MyArray[1][1]

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:

Index Data
1 Carrots
2 Beans

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[1] = "Carrots">

The value can be output on a page like this:

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

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:

MyArray[1][1]

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:

MyArray[1][1][1]

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[2] = "Bread">
<cfset MyArray[3] = "Candy Bar">
<cfset MyArray[4] = "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>
</cfloop>

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.

Array Functions
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.
This is not a complete list of functions, but it does contain some of the more common ones. A complete list is located in the Macromedia documentation, at http://livedocs.macromedia.com/coldfusion/6.1/ htmldocs/functio3.htm#wp3473387.

Conclusion
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.

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 (1)

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.