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:

Copy to Clipboard
<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...

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

So, using our prior example, we could write:

Copy to Clipboard
<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?

Copy to Clipboard

Modifying the Contents of an Array

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

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

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

Copy to Clipboard
<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):

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

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!

Sponsored Link: Design CODE-FREE Websites

Check a Domain:

ZappyHost Logo