Basic array techniques

ColdFusion arrays are a fundamental part of writing programs in ColdFusion. 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.

Create an array

In ColdFusion, you can create arrays explicitly, by using a function to declare the array and then assigning it data, or implicitly by using an assignment statement. You can create simple or complex, multidimensional arrays.

To create an array explicitly, you use the ArrayNew function and specify the array dimensions, as in the following example:

myArray=ArrayNew(2)
myArray=ArrayNew(2)
myArray=ArrayNew(2)

This statement creates a two-dimensional array named myArray. You use this method to create an array with up to three dimensions.

After you create an array, you can add array elements, which you can then reference by using the element indexes.

For example, you can create a one-dimensional array called firstName:

firstName=ArrayNew(1)
firstName=ArrayNew(1)
firstName=ArrayNew(1)

The array firstName does not hold any data. When you add data into the array, as shown below:

firstName[2]=”John”
firstName[3]=”Jason”
firstName[2]=”John” firstName[3]=”Jason”
firstName[2]=”John”
firstName[3]=”Jason”

The array has a length of three. When you dump the array contents, you get the following output:

You can also create arrays implicitly. To create an array implicitly, you use a new variable name on the left side of an assignment statement, and an array notation on the right side of the statement, as in the following example:

firstNameImplicit=[“John”,”Jason”,”James”]
firstNameImplicit=[“John”,”Jason”,”James”]
firstNameImplicit=[“John”,”Jason”,”James”]

This single statement is equivalent to the four statements used to create the firstname array in Creating arrays using functions.

When you create an array implicitly, the right side of the assignment statement has square brackets ([]) surrounding the array contents and commas separating the individual array elements. The elements can be literal values, such as the strings in the example, variables, or expressions. If you specify variables, do not place the variable names in quotation marks.

You can create an empty array implicitly, as in the following example:

myArray=[]
myArray=[]
myArray=[]

You can also create an array implicitly by assigning a single entry, as the following example shows:

myArray[1]=”ColdFusion”
myArray[1]=”ColdFusion”
myArray[1]=”ColdFusion”

In ColdFusion, you can also allow nested implicit creation of arrays, structures, or arrays and structures. For example,

jazzmen = [["Coleman","Charlie"],["Hawkins", "Parker"]]
jazzmen = [["Coleman","Charlie"],["Hawkins", "Parker"]]
jazzmen = [["Coleman","Charlie"],["Hawkins", "Parker"]]

To create a two-dimensional array, for example, use a format such as the following:

cp = ["Charlie", "Parker"]
dg = ["Dexter", "Gordon"]
cp = ["Charlie", "Parker"] dg = ["Dexter", "Gordon"]
cp = ["Charlie", "Parker"]
dg = ["Dexter", "Gordon"]

Tying them all, you have the following code:

<cfscript>
cp = ["Charlie", "Parker"]
dg = ["Dexter", "Gordon"]
jazzmen = [["Coleman","Charlie"],["Hawkins", "Parker"]]
players=[cp,dg,jazzmen]
writeDump(players)
</cfscript>
<cfscript> cp = ["Charlie", "Parker"] dg = ["Dexter", "Gordon"] jazzmen = [["Coleman","Charlie"],["Hawkins", "Parker"]] players=[cp,dg,jazzmen] writeDump(players) </cfscript>
<cfscript>
    cp = ["Charlie", "Parker"]
    dg = ["Dexter", "Gordon"]
    jazzmen = [["Coleman","Charlie"],["Hawkins", "Parker"]]
    players=[cp,dg,jazzmen]
    writeDump(players)
</cfscript>

Output

Create a multi-dimensional array

ColdFusion supports dynamic multidimensional arrays. When you declare an array with the ArrayNew function, you specify the number of dimensions. You can create an asymmetrical array or increase the number of dimensions by nesting arrays as array elements.

It is important to know that when you assign one array (array1) to an element of another array (array2), array1 is copied into array2. The original copy of array1 still exists, independent of array2. You can then change the contents of the two arrays independently.

The best way to understand an asymmetrical array is by looking at it. The following example creates an asymmetric, multidimensional, array, and the cfdump tag displays the resulting array structure. Several array elements do not yet contain data.

 

<cfscript>
myotherarray=ArrayNew(2);
biggerarray=ArrayNew(3);
myarray=[];
biggerarray[1][1][1]=myarray;
biggerarray[1][1][1][10]=3;
biggerarray[2][1][1]=myotherarray;
biggerarray[2][1][1][4][2]="five deep";
biggestarray=ArrayNew(3);
biggestarray[3][1][1]=biggerarray;
biggestarray[3][1][1][2][3][1]="This is complex";
myarray[3]="Can you see me";
writeDump(biggestarray);
writeDump(myarray);
</cfscript>
<cfscript> myotherarray=ArrayNew(2); biggerarray=ArrayNew(3); myarray=[]; biggerarray[1][1][1]=myarray; biggerarray[1][1][1][10]=3; biggerarray[2][1][1]=myotherarray; biggerarray[2][1][1][4][2]="five deep"; biggestarray=ArrayNew(3); biggestarray[3][1][1]=biggerarray; biggestarray[3][1][1][2][3][1]="This is complex"; myarray[3]="Can you see me"; writeDump(biggestarray); writeDump(myarray); </cfscript>
<cfscript>
    myotherarray=ArrayNew(2);
    biggerarray=ArrayNew(3);
    myarray=[];
    biggerarray[1][1][1]=myarray;
    biggerarray[1][1][1][10]=3;
    biggerarray[2][1][1]=myotherarray;
    biggerarray[2][1][1][4][2]="five deep";
    biggestarray=ArrayNew(3);
    biggestarray[3][1][1]=biggerarray;
    biggestarray[3][1][1][2][3][1]="This is complex";
    myarray[3]="Can you see me";
    writeDump(biggestarray);
    writeDump(myarray);
</cfscript>

Output

Deconstructing the code, we have:

1. Create three empty arrays, a 2D, 3D, and a 1D array respectively.

myotherarray=ArrayNew(2);
biggerarray=ArrayNew(3);
myarray=[]
myotherarray=ArrayNew(2); biggerarray=ArrayNew(3); myarray=[]
myotherarray=ArrayNew(2);
biggerarray=ArrayNew(3);
myarray=[]

2. Make element [1][1][1] of the 3D array a copy of the 1D array.

biggerarray[1][1][1]=myarray;
biggerarray[1][1][1]=myarray;
biggerarray[1][1][1]=myarray;

3. Assign 3 to the [1][1][1][10] element of the resulting array. The biggerarray array is now asymmetric. For example, it does not have a [1][1][2][1] element.

biggerarray[1][1][1][10]=3;
biggerarray[1][1][1][10]=3;
biggerarray[1][1][1][10]=3;

4. Make element [2][1][1] of the 3D array be the 2D array.

biggerarray[2][1][1]=myotherarray;
biggerarray[2][1][1]=myotherarray;
biggerarray[2][1][1]=myotherarray;

5. Assign the [2][1][1][4][2] element the value "five deep". The biggerarray array is now even more asymmetric.

biggerarray[2][1][1][4][2]="five deep";
biggerarray[2][1][1][4][2]="five deep";
biggerarray[2][1][1][4][2]="five deep";

6. Create a second 3D array.

biggestarray=ArrayNew(3);
biggestarray=ArrayNew(3);
biggestarray=ArrayNew(3);

7. Make the element in [3][1][1] of this array a copy of the biggerarray array and assign an element to [3][1][1][2][3][1]. The resulting array is complex and asymmetric.

biggestarray[3][1][1][2][3][1]="This is complex";
biggestarray[3][1][1][2][3][1]="This is complex";
biggestarray[3][1][1][2][3][1]="This is complex";

8. Assign a value to element 3 of myarray.

myarray[3]="Can you see me";
myarray[3]="Can you see me";
myarray[3]="Can you see me";

9. Use writeDump to view the structure of biggestarray and myarray. Notice that the "Can you see me" entry appears in myarray, but not in biggestarray, because biggestarray has a copy of the original myarray values and the change to myarray does not affect it.

writeDump(biggestarray);
writeDump(biggestarray);
writeDump(biggestarray);

Trailing comma on last element in arrays

In ColdFusion, you can add a trailing comma when creating arrays, structs, functions, parameters, and array/struct destructuring. You can add a trailing comma in the following:

  • Array literals
  • Struct literals
  • Parameter definitions
  • Function calls
  • Array and object destructuring

The trailing comma is optional.

For example,

<cfscript>
arrayVar = [
"One",
"Two",
"Three",
]
writeDump(arrayVar)
arrayVar = [
{name: "Hank"},
{name: "Dale"},
];
</cfscript>
<cfscript> arrayVar = [ "One", "Two", "Three", ] writeDump(arrayVar) arrayVar = [ {name: "Hank"}, {name: "Dale"}, ]; </cfscript>
<cfscript>
        arrayVar = [
        "One",
        "Two",
        "Three",
    ]
    writeDump(arrayVar)
    arrayVar = [
        {name: "Hank"},
        {name: "Dale"},
    ];
</cfscript>

More examples:

Example 1- using an array of mixed data types

 

<cfscript>
// Define an array of mixed data types with trailing commas
data = [
{ "name": "Alice", "age": 30, "isActive": true, "joinDate": createDate(2021, 5, 15,), },
{ "name": "Bob", "age": 25, "isActive": false, "joinDate": createDate(2022, 6, 20,), },
{ "name": "Charlie", "age": 35, "isActive": true, "joinDate": createDate(2023, 7, 25,), },
];
// Output the values to check if trailing commas are handled
output = "";
for (item in data) {
output &= item.name & "," & item.age & "," & item.isActive & "," & dateFormat(item.joinDate, "yyyy-mm-dd") & ",";
}
writeOutput(output);
</cfscript>
<cfscript> // Define an array of mixed data types with trailing commas data = [ { "name": "Alice", "age": 30, "isActive": true, "joinDate": createDate(2021, 5, 15,), }, { "name": "Bob", "age": 25, "isActive": false, "joinDate": createDate(2022, 6, 20,), }, { "name": "Charlie", "age": 35, "isActive": true, "joinDate": createDate(2023, 7, 25,), }, ]; // Output the values to check if trailing commas are handled output = ""; for (item in data) { output &= item.name & "," & item.age & "," & item.isActive & "," & dateFormat(item.joinDate, "yyyy-mm-dd") & ","; } writeOutput(output); </cfscript>
<cfscript>
        // Define an array of mixed data types with trailing commas
        data = [
            { "name": "Alice", "age": 30, "isActive": true, "joinDate": createDate(2021, 5, 15,), },
            { "name": "Bob", "age": 25, "isActive": false, "joinDate": createDate(2022, 6, 20,), },
            { "name": "Charlie", "age": 35, "isActive": true, "joinDate": createDate(2023, 7, 25,), },
        ];
        // Output the values to check if trailing commas are handled
        output = "";
        for (item in data) {
            output &= item.name & "," & item.age & "," & item.isActive & "," & dateFormat(item.joinDate, "yyyy-mm-dd") & ",";
        }
        writeOutput(output);
</cfscript>

Output

Alice,30,true,2021-05-15,Bob,25,false,2022-06-20,Charlie,35,true,2023-07-25,

Example 2- using IIFE with trailing commas

 

<cfscript>
// IIFE to filter even numbers from an array with a trailing comma
result = (function(test,) {
// Creating an array with trailing commas
numbers = [1, 2, 3, 4, 5, 6,]
// Array to hold filtered even numbers
evenNumbers = [];
// Filter even numbers
for (num in numbers) {
if (num % 2 == 0) {
arrayAppend(evenNumbers, num)
}
}
return evenNumbers; // Return the filtered even numbers
})(); // Immediately invoke the function
// Output the result as a comma-separated string
writeOutput("Even Numbers: " & arrayToList(result));
</cfscript>
<cfscript> // IIFE to filter even numbers from an array with a trailing comma result = (function(test,) { // Creating an array with trailing commas numbers = [1, 2, 3, 4, 5, 6,] // Array to hold filtered even numbers evenNumbers = []; // Filter even numbers for (num in numbers) { if (num % 2 == 0) { arrayAppend(evenNumbers, num) } } return evenNumbers; // Return the filtered even numbers })(); // Immediately invoke the function // Output the result as a comma-separated string writeOutput("Even Numbers: " & arrayToList(result)); </cfscript>
<cfscript>
        // IIFE to filter even numbers from an array with a trailing comma
        result = (function(test,) {
            // Creating an array with trailing commas
            numbers = [1, 2, 3, 4, 5, 6,]
            
            // Array to hold filtered even numbers
            evenNumbers = [];
            // Filter even numbers
            for (num in numbers) {
                if (num % 2 == 0) {
                    arrayAppend(evenNumbers, num)
                }
            }
            return evenNumbers; // Return the filtered even numbers
        })(); // Immediately invoke the function
        // Output the result as a comma-separated string
        writeOutput("Even Numbers: " & arrayToList(result));
</cfscript>

Output

Even Numbers: 2,4,6

Example 3- Using query objects with array of structs and trailing commas

 

<cfscript>
data = [
{ "name": "Alice", "age": 30, },
{ "name": "Bob", "age": 25, },
{ "name": "Charlie", "age": 35, },
];
// Create a query object using QueryNew
queryObj = QueryNew("name,age,");
// Insert data into the query object
for (row in data) {
QueryAddRow(queryObj,); // Add a new row
// Set the values for the current row
QuerySetCell(queryObj, "name", row.name, queryObj.recordCount,);
QuerySetCell(queryObj, "age", row.age, queryObj.recordCount,);
}
// Output the values to check if trailing commas are handled
output = "";
for (i = 1; i <= queryObj.recordCount; i++) {
output &= queryObj.name[i] & "," & queryObj.age[i] & ",";
}
writeOutput(output);
</cfscript>
<cfscript> data = [ { "name": "Alice", "age": 30, }, { "name": "Bob", "age": 25, }, { "name": "Charlie", "age": 35, }, ]; // Create a query object using QueryNew queryObj = QueryNew("name,age,"); // Insert data into the query object for (row in data) { QueryAddRow(queryObj,); // Add a new row // Set the values for the current row QuerySetCell(queryObj, "name", row.name, queryObj.recordCount,); QuerySetCell(queryObj, "age", row.age, queryObj.recordCount,); } // Output the values to check if trailing commas are handled output = ""; for (i = 1; i <= queryObj.recordCount; i++) { output &= queryObj.name[i] & "," & queryObj.age[i] & ","; } writeOutput(output); </cfscript>
<cfscript>
        data = [
            { "name": "Alice", "age": 30, },
            { "name": "Bob", "age": 25, },
            { "name": "Charlie", "age": 35, },
        ];
        // Create a query object using QueryNew
        queryObj = QueryNew("name,age,");
        // Insert data into the query object
        for (row in data) {
            QueryAddRow(queryObj,); // Add a new row
            // Set the values for the current row
            QuerySetCell(queryObj, "name", row.name, queryObj.recordCount,);
            QuerySetCell(queryObj, "age", row.age, queryObj.recordCount,);
        }
        // Output the values to check if trailing commas are handled
        output = "";
        for (i = 1; i <= queryObj.recordCount; i++) {
            output &= queryObj.name[i] & "," & queryObj.age[i] & ",";
        }
        writeOutput(output);
</cfscript>

Output

Alice,30,Bob,25,Charlie,35,

Example 4- using serializeJSON with trailing comma

 

<cfscript>
myArray = [1, 2,]
// Serializing the array to JSON
jsonOutput = serializeJSON(myArray)
// Outputting the serialized JSON
writeOutput(jsonOutput)
</cfscript>
<cfscript> myArray = [1, 2,] // Serializing the array to JSON jsonOutput = serializeJSON(myArray) // Outputting the serialized JSON writeOutput(jsonOutput) </cfscript>
<cfscript>
        myArray = [1, 2,]
        // Serializing the array to JSON
        jsonOutput = serializeJSON(myArray)
        // Outputting the serialized JSON
        writeOutput(jsonOutput)
</cfscript>

More examples

<cfscript>
arrayVar = [
"One",
"Two",
"Three",
];
writedump(arrayVar)
</cfscript>
<cfscript> arrayVar = [ "One", "Two", "Three", ]; writedump(arrayVar) </cfscript>
<cfscript>
    arrayVar = [
      "One",
      "Two",
      "Three",
    ];
 writedump(arrayVar)
</cfscript>
<cfscript>
arrayVar = [
{name: "Tom"},
{name: "Jones"},
];
writedump(arrayVar)
</cfscript>
<cfscript> arrayVar = [ {name: "Tom"}, {name: "Jones"}, ]; writedump(arrayVar) </cfscript>
<cfscript>
    arrayVar = [
      {name: "Tom"},
      {name: "Jones"},
    ];
 writedump(arrayVar)
 </cfscript>
<cfscript>
function f(p,) {}
</cfscript>
<cfscript> function f(p,) {} </cfscript>
<cfscript>
     function f(p,) {}
</cfscript>
<cfscript>
o = {
p: 42,
q: true,
};
({ p, q, } = o);
writedump(p)
</cfscript>
<cfscript> o = { p: 42, q: true, }; ({ p, q, } = o); writedump(p) </cfscript>
<cfscript>
   o = {
      p: 42,
      q: true,
    };

    ({ p, q, } = o);
    writedump(p)
</cfscript>

Create multi-dimensional array using JavaCast function

The javaCast function in ColdFusion is used to explicitly cast a value to a specific Java type. You can use this function with Java objects or calling Java methods from ColdFusion code and need to ensure that the values you pass are of the correct Java type.

In versions prior to ColdFusion (2025 release), JavaCast() only supports casting to a one-dimensional array, for example, JavaCast("long[]", value). For example,

<cfscript>
// create a 1D array
cfArray = [1, 2, 3, 4, 5]
// prepare the Java 1D array
javaArray = ArrayNew(1);
for (i = 1; i <= ArrayLen(cfArray); i++) {
ArrayAppend(javaArray, javacast("int", cfArray[i]));
}
java1DArray = javacast("int[]", javaArray)
// output
WriteDump(java1DArray)
</cfscript>
<cfscript> // create a 1D array cfArray = [1, 2, 3, 4, 5] // prepare the Java 1D array javaArray = ArrayNew(1); for (i = 1; i <= ArrayLen(cfArray); i++) { ArrayAppend(javaArray, javacast("int", cfArray[i])); } java1DArray = javacast("int[]", javaArray) // output WriteDump(java1DArray) </cfscript>
<cfscript>
    // create a 1D array
    cfArray = [1, 2, 3, 4, 5]

    // prepare the Java 1D array
    javaArray = ArrayNew(1);
    for (i = 1; i <= ArrayLen(cfArray); i++) {
        ArrayAppend(javaArray, javacast("int", cfArray[i]));
    }
    java1DArray = javacast("int[]", javaArray)

    // output
    WriteDump(java1DArray)
</cfscript>

In ColdFusion (2025 release), you can use JavaCast to create multi-dimensional arrays.

Here’s some examples to get you started.

Example 1- Using int data type

 

<cfscript>
// create a 2D array
my2DArray = ArrayNew(2);
// populate the 2D array with float values
my2DArray[1][1] = 1.1;
my2DArray[1][2] = 1.2;
my2DArray[1][3] = 1.3;
my2DArray[2][1] = 2.1;
my2DArray[2][2] = 2.2;
my2DArray[2][3] = 2.3;
my2DArray[3][1] = 3.1;
my2DArray[3][2] = 3.2;
my2DArray[3][3] = 3.3;
// cast as Java array
java2DArray=JavaCast("int[][]", my2DArray)
writeDump(java2DArray)
</cfscript>
<cfscript> // create a 2D array my2DArray = ArrayNew(2); // populate the 2D array with float values my2DArray[1][1] = 1.1; my2DArray[1][2] = 1.2; my2DArray[1][3] = 1.3; my2DArray[2][1] = 2.1; my2DArray[2][2] = 2.2; my2DArray[2][3] = 2.3; my2DArray[3][1] = 3.1; my2DArray[3][2] = 3.2; my2DArray[3][3] = 3.3; // cast as Java array java2DArray=JavaCast("int[][]", my2DArray) writeDump(java2DArray) </cfscript>
<cfscript>
    // create a 2D array
    my2DArray = ArrayNew(2);

    // populate the 2D array with float values
    my2DArray[1][1] = 1.1;
    my2DArray[1][2] = 1.2;
    my2DArray[1][3] = 1.3;

    my2DArray[2][1] = 2.1;
    my2DArray[2][2] = 2.2;
    my2DArray[2][3] = 2.3;

    my2DArray[3][1] = 3.1;
    my2DArray[3][2] = 3.2;
    my2DArray[3][3] = 3.3;

    // cast as Java array
    java2DArray=JavaCast("int[][]", my2DArray)
    writeDump(java2DArray)
</cfscript>

Example 2- Using long data type

 

<cfscript>
// create a 2d array
my2DArray = ArrayNew(2)
// populate the 2D array
my2DArray[1][1] = randRange(500000,1000000)
my2DArray[1][2] = randRange(500000,1000000)
my2DArray[1][3] = randRange(500000,1000000)
my2DArray[2][1] = randRange(500000,1000000)
my2DArray[2][2] = randRange(500000,1000000)
my2DArray[2][3] = randRange(500000,1000000)
my2DArray[3][1] = randRange(500000,1000000)
my2DArray[3][2] = randRange(500000,1000000)
my2DArray[3][3] = randRange(500000,1000000)
// cast as Java array
java2DArray=JavaCast("long[][]", my2DArray)
writeDump(java2DArray)
</cfscript>
<cfscript> // create a 2d array my2DArray = ArrayNew(2) // populate the 2D array my2DArray[1][1] = randRange(500000,1000000) my2DArray[1][2] = randRange(500000,1000000) my2DArray[1][3] = randRange(500000,1000000) my2DArray[2][1] = randRange(500000,1000000) my2DArray[2][2] = randRange(500000,1000000) my2DArray[2][3] = randRange(500000,1000000) my2DArray[3][1] = randRange(500000,1000000) my2DArray[3][2] = randRange(500000,1000000) my2DArray[3][3] = randRange(500000,1000000) // cast as Java array java2DArray=JavaCast("long[][]", my2DArray) writeDump(java2DArray) </cfscript>
<cfscript>
    // create a 2d array
    my2DArray = ArrayNew(2)
    
    // populate the 2D array
    my2DArray[1][1] = randRange(500000,1000000)
    my2DArray[1][2] = randRange(500000,1000000)
    my2DArray[1][3] = randRange(500000,1000000)

    my2DArray[2][1] = randRange(500000,1000000)
    my2DArray[2][2] = randRange(500000,1000000)
    my2DArray[2][3] = randRange(500000,1000000)

    my2DArray[3][1] = randRange(500000,1000000)
    my2DArray[3][2] = randRange(500000,1000000)
    my2DArray[3][3] = randRange(500000,1000000)

    // cast as Java array
    java2DArray=JavaCast("long[][]", my2DArray)
    writeDump(java2DArray)
</cfscript> 

Example 3- Using float data type

 

<cfscript>
// create a 2D array
my2DArray = ArrayNew(2);
// populate the 2D array with float values
my2DArray[1][1] = 1.1;
my2DArray[1][2] = 1.2;
my2DArray[1][3] = 1.3;
my2DArray[2][1] = 2.1;
my2DArray[2][2] = 2.2;
my2DArray[2][3] = 2.3;
my2DArray[3][1] = 3.1;
my2DArray[3][2] = 3.2;
my2DArray[3][3] = 3.3;
// cast as Java array
java2DArray=JavaCast("float[][]", my2DArray)
writeDump(java2DArray)
</cfscript>
<cfscript> // create a 2D array my2DArray = ArrayNew(2); // populate the 2D array with float values my2DArray[1][1] = 1.1; my2DArray[1][2] = 1.2; my2DArray[1][3] = 1.3; my2DArray[2][1] = 2.1; my2DArray[2][2] = 2.2; my2DArray[2][3] = 2.3; my2DArray[3][1] = 3.1; my2DArray[3][2] = 3.2; my2DArray[3][3] = 3.3; // cast as Java array java2DArray=JavaCast("float[][]", my2DArray) writeDump(java2DArray) </cfscript>
<cfscript>
    // create a 2D array
    my2DArray = ArrayNew(2);

    // populate the 2D array with float values
    my2DArray[1][1] = 1.1;
    my2DArray[1][2] = 1.2;
    my2DArray[1][3] = 1.3;

    my2DArray[2][1] = 2.1;
    my2DArray[2][2] = 2.2;
    my2DArray[2][3] = 2.3;

    my2DArray[3][1] = 3.1;
    my2DArray[3][2] = 3.2;
    my2DArray[3][3] = 3.3;

    // cast as Java array
    java2DArray=JavaCast("float[][]", my2DArray)
    writeDump(java2DArray)
</cfscript>

If you cast an array of float data type to int, the output array is cast as int. For example,

 

<cfscript>
// create a 2D array
my2DArray = ArrayNew(2);
// populate the 2D array with float values
my2DArray[1][1] = 1.1;
my2DArray[1][2] = 1.2;
my2DArray[1][3] = 1.3;
my2DArray[2][1] = 2.1;
my2DArray[2][2] = 2.2;
my2DArray[2][3] = 2.3;
my2DArray[3][1] = 3.1;
my2DArray[3][2] = 3.2;
my2DArray[3][3] = 3.3;
// cast as Java array
java2DArray=JavaCast("int[][]", my2DArray)
writeDump(java2DArray)
</cfscript>
<cfscript> // create a 2D array my2DArray = ArrayNew(2); // populate the 2D array with float values my2DArray[1][1] = 1.1; my2DArray[1][2] = 1.2; my2DArray[1][3] = 1.3; my2DArray[2][1] = 2.1; my2DArray[2][2] = 2.2; my2DArray[2][3] = 2.3; my2DArray[3][1] = 3.1; my2DArray[3][2] = 3.2; my2DArray[3][3] = 3.3; // cast as Java array java2DArray=JavaCast("int[][]", my2DArray) writeDump(java2DArray) </cfscript>
<cfscript>
    // create a 2D array
    my2DArray = ArrayNew(2);

    // populate the 2D array with float values
    my2DArray[1][1] = 1.1;
    my2DArray[1][2] = 1.2;
    my2DArray[1][3] = 1.3;

    my2DArray[2][1] = 2.1;
    my2DArray[2][2] = 2.2;
    my2DArray[2][3] = 2.3;

    my2DArray[3][1] = 3.1;
    my2DArray[3][2] = 3.2;
    my2DArray[3][3] = 3.3;

    // cast as Java array
    java2DArray=JavaCast("int[][]", my2DArray)
    writeDump(java2DArray)
</cfscript>

Add elements to an array

You can use the following array functions to add data to an array:

ArrayAppend

The ArrayAppend function an array element to an array.  Concatenates arrays when the merge argument is set to true and the value argument is an array.

For example,

 

<cfscript>
myArray=[1,3,5,7,9]
toAppend=ArrayAppend(myArray,11,true)
writeOutput("Is the value appended successfully?" & toAppend & "<br/>")
writeOutput("The modified array is:")
writeDump(myArray)
</cfscript>
<cfscript> myArray=[1,3,5,7,9] toAppend=ArrayAppend(myArray,11,true) writeOutput("Is the value appended successfully?" & toAppend & "<br/>") writeOutput("The modified array is:") writeDump(myArray) </cfscript>
<cfscript>
    myArray=[1,3,5,7,9]
    toAppend=ArrayAppend(myArray,11,true)
    writeOutput("Is the value appended successfully?" & toAppend & "<br/>")
    writeOutput("The modified array is:")
    writeDump(myArray)
</cfscript>

Output

ArrayPrepend

The ArrayPrepend function inserts an array element at the beginning of an array.

For example,

 

<cfscript>
myArray=[3,5,7,9,11]
toPrepend=ArrayPrepend(myArray,1)
writeOutput("Is the value pre-pended successfully?" & toPrepend & "<br/>")
writeOutput("The modified array is:")
writeDump(myArray)
</cfscript>
<cfscript> myArray=[3,5,7,9,11] toPrepend=ArrayPrepend(myArray,1) writeOutput("Is the value pre-pended successfully?" & toPrepend & "<br/>") writeOutput("The modified array is:") writeDump(myArray) </cfscript>
<cfscript>
    myArray=[3,5,7,9,11]
    toPrepend=ArrayPrepend(myArray,1)
    writeOutput("Is the value pre-pended successfully?" & toPrepend & "<br/>")
    writeOutput("The modified array is:")
    writeDump(myArray)
</cfscript>

Output

ArrayInsertAt

The ArrayInsertAt function inserts a value into an array. Array elements whose indexes are equal to or greater than the new position is incremented by one.

For example,

 

<cfscript>
myCities=["London","New York","Paris","Tokyo","Barcelona"];
myNewCity="Berlin,Prague,Rome"
ArrayInsertAt(myCities,4,myNewCity)
writeOutput("The updated array is:")
writeDump(myCities)
</cfscript>
<cfscript> myCities=["London","New York","Paris","Tokyo","Barcelona"]; myNewCity="Berlin,Prague,Rome" ArrayInsertAt(myCities,4,myNewCity) writeOutput("The updated array is:") writeDump(myCities) </cfscript>
<cfscript>
    myCities=["London","New York","Paris","Tokyo","Barcelona"];
    myNewCity="Berlin,Prague,Rome"
    ArrayInsertAt(myCities,4,myNewCity)
    writeOutput("The updated array is:")
    writeDump(myCities)
</cfscript>

Output

Delete elements in an array

You can use the following functions to delete elements from an array.

ArrayDelete

The ArrayDelete function searches an array for the first position of a specified object and deletes it.

For example,

 

<cfscript>
myArray=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"];
ArrayDelete(myArray,"Paris")
writeOutput("The modified array is:")
writeDump(myArray)
</cfscript>
<cfscript> myArray=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"]; ArrayDelete(myArray,"Paris") writeOutput("The modified array is:") writeDump(myArray) </cfscript>
<cfscript>
    myArray=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"];
    ArrayDelete(myArray,"Paris")
    writeOutput("The modified array is:")
    writeDump(myArray)
</cfscript>

Output

ArrayDeleteAt

The ArrayDeleteAt function deletes an element from a specified position in an array.

For example,

 

<cfscript>
myArray=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"];
// Delete element at 4th position
ArrayDeleteAt(myArray,4)
writeOutput("The modified array is:")
writeDump(myArray)
</cfscript>
<cfscript> myArray=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"]; // Delete element at 4th position ArrayDeleteAt(myArray,4) writeOutput("The modified array is:") writeDump(myArray) </cfscript>
<cfscript>
    myArray=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"];
    // Delete element at 4th position
    ArrayDeleteAt(myArray,4)
    writeOutput("The modified array is:")
    writeDump(myArray)
</cfscript>

Output

Loop over arrays

You can use different constructs for looping over arrays:

  • for loops
  • cfloop tag
  • ArrayEach closures

For loop

You can use for loops, as shown below:

 

<cfscript>
myCities=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"];
// for loop
for (i=1;i<=ArrayLen(myCities);i++){
writeOutput("The city is:" & myCities[i] & "<br/>")
}
</cfscript>
<cfscript> myCities=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"]; // for loop for (i=1;i<=ArrayLen(myCities);i++){ writeOutput("The city is:" & myCities[i] & "<br/>") } </cfscript>
<cfscript>
    myCities=["London", "New York", "Paris", "Barcelona", "Berlin", "Tokyo", "Seattle"];
    // for loop
    for (i=1;i<=ArrayLen(myCities);i++){
        writeOutput("The city is:" & myCities[i] & "<br/>")
    }
</cfscript>

Output

The city is:London

The city is:New York

The city is:Paris

The city is:Barcelona

The city is:Berlin

The city is:Tokyo

The city is:Seattle

cfloop tag

You can use for constructs, as shown below:

 

<cfset myArray = ["Australia", "Brazil", "Canada"]>
<!--- By index --->
<cfloop index="i" from="1" to="#arrayLen(myArray)#">
<cfoutput>#myArray[i]#</cfoutput>
</cfloop>
<br/>
<!--- By array --->
<cfloop index="currentIndex" array="#myArray#">
<cfoutput>#currentIndex#</cfoutput>
</cfloop>
<cfset myArray = ["Australia", "Brazil", "Canada"]> <!--- By index ---> <cfloop index="i" from="1" to="#arrayLen(myArray)#"> <cfoutput>#myArray[i]#</cfoutput> </cfloop> <br/> <!--- By array ---> <cfloop index="currentIndex" array="#myArray#"> <cfoutput>#currentIndex#</cfoutput> </cfloop>
<cfset myArray = ["Australia", "Brazil", "Canada"]> 
 <!--- By index ---> 
 <cfloop index="i" from="1" to="#arrayLen(myArray)#"> 
 <cfoutput>#myArray[i]#</cfoutput>
 </cfloop>
 <br/>
 <!--- By array ---> 
 <cfloop index="currentIndex" array="#myArray#"> 
 <cfoutput>#currentIndex#</cfoutput> 
 </cfloop>

For more information on cfloop on arrays, see cfloop-Arrays.

Output

Australia Brazil Canada 
Australia Brazil Canada

ArrayEach

You can use ArrayEach, as shown below:

 

<cfscript>
myCities=["London","New York","Paris","Tokyo","Barcelona"];
// Create a function that takes city as an argument and prints the name of the cities as output
// with delimiter as space
ArrayEach(myCities,function(city){
WriteOutput("City is: " & city & "<br/>");
}
);
</cfscript>
<cfscript> myCities=["London","New York","Paris","Tokyo","Barcelona"]; // Create a function that takes city as an argument and prints the name of the cities as output // with delimiter as space ArrayEach(myCities,function(city){ WriteOutput("City is: " & city & "<br/>"); } ); </cfscript>
<cfscript>
       myCities=["London","New York","Paris","Tokyo","Barcelona"];
       // Create a function that takes city as an argument  and prints the name of the cities as output
       // with delimiter as space
       ArrayEach(myCities,function(city){
             WriteOutput("City is: " & city & "<br/>");
             }
       );
</cfscript>

Output

City is: London

City is: New York

City is: Paris

City is: Tokyo

City is: Barcelona

Functional programming with arrays

Using functional programming techniques, you can write code that is relatively bug-free, easier to debug and test, and easier to refactor.

One of the reasons why functional programming has become popular is its ability to manipulate data structures easily and efficiently when compared to traditional methods.

ArrayMap

The ArrayMap function operates on all elements of an array and produces an array of the same dimension with transformed values.

For example,

 

<cfscript>
myArray=[1,2,3,4,5]
ArrayMap(myArray,function(x){
doubled[x]=x*2 // each value of the original array is doubled by the closure function
})
writeDUmp(doubled)
</cfscript>
<cfscript> myArray=[1,2,3,4,5] ArrayMap(myArray,function(x){ doubled[x]=x*2 // each value of the original array is doubled by the closure function }) writeDUmp(doubled) </cfscript>
<cfscript>
    myArray=[1,2,3,4,5]
    ArrayMap(myArray,function(x){
        doubled[x]=x*2 // each value of the original array is doubled by the closure function
    })
    writeDUmp(doubled)
</cfscript>

Output

ArrayReduce

The ArrayReduce function “reduces” an array to a single value.

For example,

 

<cfscript>
data = [1,2,3,4,5,6];
sum=data.reduce(function(previous,next) {
return previous+next;
},0);
writeOutput(sum); // Output is 21
</cfscript>
<cfscript> data = [1,2,3,4,5,6]; sum=data.reduce(function(previous,next) { return previous+next; },0); writeOutput(sum); // Output is 21 </cfscript>
<cfscript>
       data = [1,2,3,4,5,6];
       sum=data.reduce(function(previous,next) {
       return previous+next;
       },0);
       writeOutput(sum); // Output is 21
</cfscript>

Let’s deconstruct the code- The reduce function takes a callback function and an initial value as parameters. The callback function uses the parameters previous and next to add a current array element to its preceding element. When the function reaches the end of the array, the output is the sum of all elements in the input array.

ArrayFilter

The ArrayFilter function filters the elements in an array for which the inline function returns true.

For example,

 

<cfscript>
myArray=[1,2,3,4,5,6,7,8,9]
evenArray=ArrayFilter(myArray,function(item){
return (item mod 2==0)
})
writeOutput("The array of even numbers is:")
writeDump(evenArray)
</cfscript>
<cfscript> myArray=[1,2,3,4,5,6,7,8,9] evenArray=ArrayFilter(myArray,function(item){ return (item mod 2==0) }) writeOutput("The array of even numbers is:") writeDump(evenArray) </cfscript>
<cfscript>
    myArray=[1,2,3,4,5,6,7,8,9]
    evenArray=ArrayFilter(myArray,function(item){
        return (item mod 2==0)
    })
    writeOutput("The array of even numbers is:")
    writeDump(evenArray)
</cfscript>

Output

Other array functions

Copy an array

You can copy arrays of simple variables (numbers, strings, Boolean values, and date-time values) by assigning the original array to a new variable name.

When you assign the existing array to a new variable, ColdFusion creates an array and copies the contents of the old array to the new array. The following example creates and populates a two-element array. It then copies the original array, changes one element of the copied array and dumps both arrays. As you can see, the original array is unchanged and the copy has a new second element.

For more information, see Duplicate.

For example,

<cfscript>
myArray[1]="First Array Element";
myArray[2]="Second Array Element";
newArray=myArray;
newArray[2]="New Array Element 2";
writeDump(myArray);
writeDump(newArray);
</cfscript>
<cfscript> myArray[1]="First Array Element"; myArray[2]="Second Array Element"; newArray=myArray; newArray[2]="New Array Element 2"; writeDump(myArray); writeDump(newArray); </cfscript>
<cfscript>
    myArray[1]="First Array Element";
    myArray[2]="Second Array Element";
    newArray=myArray;
    newArray[2]="New Array Element 2";
    writeDump(myArray);
    writeDump(newArray);
</cfscript>

Output

Length of an array

The function ArrayLen calculates the number of elements in an array.

For example,

 

<cfscript>
myArray=[1,2,3,4,5];
writeoutput(ArrayLen(myArray)); // Returns 5
</cfscript>
<cfscript> myArray=[1,2,3,4,5]; writeoutput(ArrayLen(myArray)); // Returns 5 </cfscript>
<cfscript>
    myArray=[1,2,3,4,5];
    writeoutput(ArrayLen(myArray)); // Returns 5
</cfscript>

Get help faster and easier

New user?