One-Dimensional arrays are similar to lists or tables with a single column. An array can contain zero or more elements. In ColdFusion, unlike in many programming languages, the first element of an array has an index of 1. An array with no elements has a zero length.
Arrays are created with the built-in ArrayNew() function, which takes one argument - the number of dimensions in the array. The following line of code creates a onedimensional array and then adds four elements to the array.
The first line above is actually optional as the second line will create the array if one does not already exist. However, it is a better coding practice to explicitly set the array.
Reading from arrays is just a matter of pointing to a specific index of an array.
The following code sample shows how to create the array, output a single element in the array, and then loop through the entire array outputting each element to the browser.
<head> <title>Array Demo</title> </head> <body> <cfset beatles = ArrayNew(1)> <cfset ArrayAppend(beatles,"John")> <cfset ArrayAppend(beatles,"Paul")> <cfset ArrayAppend(beatles,"George")> <cfset ArrayAppend(beatles,"Ringo")> <!---outputs George to the browser---> <cfoutput>#beatles#</cfoutput> <ul> <cfloop from="1" to="#ArrayLen(beatles)#" index="i"> <li><cfoutput>#beatles[i]#</cfoutput></li> </cfloop> </ul> </body> </html>
Note that the code uses the
ArrayLen() function to determine the length of the array, which is the same
as the highest index. The next sections discusses other array functions.
As with lists, ColdFusion provides many built-in functions for working with arrays. The table below shows some of the most common array functions.
|ArrayNew()||Creates a new array.|
|ArrayLen()||Determines the number of elements in an array.|
|IsArray()||Returns true if value is an array; false otherwise.|
|ArrayIsEmpty()||Returns true if array has zero elements.|
|ArraySort()||Sorts array elements according to a sort type and sort order.|
|ArrayAppend()||Appends an element to an array.|
|ArrayPrepend()||Prepends an element to an array.|
|ArrayInsertAt()||Inserts a value into an array. Array elements whose indexes are greater than the new position are incremented by one. The array length increases by one.|
|ArrayDeleteAt()||Deletes an element from an array.|
|ArrayClear()||Deletes all elements from an array.|
|ArrayMin()||Returns the smallest numeric value in an array.|
|ArrayMax()||Returns the greatest numeric value in an array.|
|ArrayAvg()||Calculates the average of the values in an array.|
|ArraySum()||Calculates the sum of the values in an array.|
|ArrayResize()||Gets the first element of a list.|
|ArrayToList()||Converts a one-dimensional array to a list.|
|ListToArray()||Converts a one-dimensional array to a list.|
|ArrayToList()||Converts a list to a one-dimensional array.|