ColdFusion Arrays

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:

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.

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

then by assigning values to the array...

So, using our prior example, we could write:

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:

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

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):