ColdFusion Arrays

ColdFusion arrays (or any array) are a fundamental part of most programming languages and scripts.

An array is simply an ordered stack of data items with the same data type. Using an array, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.

For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:

<cfset faqQuestion1 = "What is an array?">
<cfset faqQuestion2 = "How to create a ColdFusion array?">
<cfset faqQuestion3 = "What are two dimensional arrays?">

This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do stuff like loop through all your variables. That's where arrays come into play. You could put all your questions into one array.

Visualizing Arrays

Arrays can be visualized as a stack of elements.

0What are ColdFusion arrays?
1How to create a ColdFusion array?
2What are two dimensional arrays?

Note: Some languages start arrays at zero, others start at 1. ColdFusion arrays start at 1.

Creating Arrays in ColdFusion

Most languages use similar syntax to create arrays. A ColdFusion array is created by first assigning an array object to a variable name...

<cfset array_name = ArrayNew(1)>
then by assigning values to the array...
<cfset ArrayAppend(array_name, {value})>

So, using our prior example, we could write:

<cfset faq = ArrayNew(1)>
<cfset ArrayAppend(faq, "What are ColdFusion arrays")>
<cfset ArrayAppend(faq, "How to create a ColdFusion array?")>
<cfset ArrayAppend(faq, "What are two dimensional arrays?")>

Accessing Arrays in ColdFusion

You can access an array element by referring to the name of the array and the element's index number.

Displaying Array Elements

The following code displays the second element of the array named faq. In this case, the value would be How to create a ColdFusion array?


Modifying the Contents of an Array

To add an item to the end of an array, use the ArrayAppend() function:

<cfset ArrayAppend(faq, "How to modify an array?")>

To add an item to the beginning of the array, use the ArrayPrepend() function:

<cfset ArrayPrepend(faq, "How to modify an array?")>

To insert an item in a specific position in the array, use the ArrayInsertAt() function (in this case, the new value is added before position 3):

<cfset ArrayInsertAt(faq, ,3, "How to modify an array?")>