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:


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:


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:


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

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.

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
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
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...
Japan DX Pavilion at @CloudEXPO Silicon Valley
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...
The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...
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...
Where many organizations get into trouble, however, is that they try to have a broad and deep knowledge in each of these areas. This is a huge blow to an organization's productivity. By automating or outsourcing some of these pieces, such as databases, infrastructure, and networks, your team can instead focus on development, testing, and deployment. Further, organizations that focus their attention on these areas can eventually move to a test-driven development structure that condenses several l...
The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
Over the course of two days, in addition to insightful conversations and presentations delving into the industry's current pressing challenges, there was considerable buzz about digital transformation and how it is enabling global enterprises to accelerate business growth. Blockchain has been a term that people hear but don't quite understand. The most common myths about blockchain include the assumption that it is private, or that there is only one blockchain, and the idea that blockchain is...
Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...