facebook google plus twitter
Webucator's Free ColdFusion MX Tutorial

Lesson: Lists and Arrays

Welcome to our free ColdFusion MX tutorial. This tutorial is based on Webucator's Comprehensive ColdFusion Training course.

Lesson Goals

  • To work with lists.
  • To work with one- and two-dimensional arrays.

Lists

Lists are really nothing more than strings delimited by a specified character or set of characters. By default, the delimiter is a comma. A list can be created using <cfset>.

<cfset numlist="1,2,3,4,5">

The delimiter can be changed to any character or group of characters

<cfset beatles="Paul John George Ringo">

To following code shows how to loop through these lists.

Code Sample:

ListsAndArrays/Demos/ListLoops.cfm
<html>
<head>
<title>List Loops</title>
</head>

<body>
<h1>List Loops</h1>

<h2>List Loop 1</h2>
<cfset numlist="1,2,3,4,5">
<cfloop index="num" list="#numlist#">
	<cfoutput>#num#</cfoutput>
</cfloop>

<h2>List Loop 2</h2>
<cfset beatles="paul john ringo george">
<ul>
<cfloop index="beatle" list="#beatles#" delimiters=" ">
	<li><cfoutput>#beatle#</cfoutput></li>
</cfloop>
</ul>

</body>
</html>

List Functions

ColdFusion provides many built-in functions for working with lists. The table below shows some of the most common list functions.

List Functions
Function Description
ListLen() Determines the number of elements in a list.
ListFind() Returns the index of the first list element in which a specified value occurs. Case-sensitive.
ListFindNoCase() Determines the index of the first list element in which a specified value occurs. Case-insensitive.
ListContains() Returns the index of the first list element that contains a specified substring. Case-sensitive.
ListContainsNoCase() Returns the index of the first list element that contains a specified substring. Case-insensitive.
ListValueCount() Counts instances of a specified value in a list. The search is case-sensitive.
ListValueCountNoCase() Counts instances of a specified value in a list. The search is case-insensitive.
ListDeleteAt() Returns a copy of the list without the specified element.
ListGetAt() Gets a list element at a specified position.
ListSetAt() Replaces the contents of a list element.
ListSort() Sorts list elements according to a sort type and sort order.
ListAppend() Appends a list or element to a list.
ListPrepend() Inserts an element at the beginning of a list.
ListInsertAt() Inserts an element in a list.
ListFirst() Gets the first element of a list.
ListRest() Gets a list, without its first element.
ListLast() Gets the last element of a list.
ArrayToList() Converts a one-dimensional array to a list.
ListToArray() Converts a list to a one-dimensional array.
ReplaceList() Replaces occurrences of the elements from a delimited list in a string with corresponding elements from another delimited list. The search is case-sensitive.
ListChangeDelims() Changes a list delimiter.
ListQualify() Inserts a string at the beginning and end of list elements.

Formatting the Running Log

Duration: 15 to 25 minutes.

In this exercise, you will change the running log so that it displays the entries in an HTML table.

  1. Open ListsAndArrays/Exercises/RunningLog.cfm in your editor.
  2. Before the loop that is used to display the entries, begin an HTML table and add a header row that contains the following table headers: Date, Distance, Time, and Comments.
  3. Write code that will create a table row. Use <cfloop> to output the table data cells.
  4. Close the HTML table.

Write code so that the resulting table's table rows have alternate colors as in the following diagram.

Note that, if you use hexadecimal color values, you may need to escape the pound sign in locations in which ColdFusion will interpret it as the beginning of an expression to be evaluated. The escape character is another pound sign. For example, the following code properly sets a variable called bgcolor.

<cfset bgcolor="##ff0000">

Solution:

ListsAndArrays/Solutions/RunningLog.cfm
<html>
<head>
  <title>Running Log</title>
</head>
<body>
<h1>Running Log</h1>
<a href="AddEntry.cfm">Add Entry</a><hr/>
<cfset RunningLogPath = ExpandPath("Logs/RunningLog.txt")>
<cfset CrLf = chr(10) & chr(13)>
<cfif FileExists(RunningLogPath)>
	<cffile action="read" file="#RunningLogPath#" variable="myfile">
	<table border="1">
	<tr>
		<th>Date</th>
		<th>Distance</th>
		<th>Time</th>
		<th>Comments</th>
	</tr>
	<cfloop list="#myfile#" index="run" delimiters="#CrLf#">
		<cfoutput>
			<tr>
			<cfloop list="#run#" index="col" delimiters="#chr(9)#">
				<td>#col#</td>
			</cfloop>
			</tr>
		</cfoutput>
	</cfloop>
	</table>
<cfelse>
	You have apparently never been running.
</cfif>

</body>
</html>

Challenge Solution:

ListsAndArrays/Solutions/RunningLog-challenge.cfm
<html>
<head>
  <title>Running Log</title>
  <style type="text/css">
  	.grayBg {background-color:#cccccc; font-style:italic;}
	.whiteBg {background-color:#ffffff; font-weight:bold}
  </style>
</head>
<body>
<h1>Running Log</h1>
<a href="AddEntry.cfm">Add Entry</a><hr/>
<cfset RunningLogPath = ExpandPath("Logs/RunningLog.txt")>
<cfset CrLf = chr(10) & chr(13)>
<cfif FileExists(RunningLogPath)>
	<cffile action="read" file="#RunningLogPath#" variable="myfile">
	<table border="1" bgcolor="#ccccff">
	<tr>
		<th>Date</th>
		<th>Distance</th>
		<th>Time</th>
		<th>Comments</th>
	</tr>
	<cfloop list="#myfile#" index="run" delimiters="#CrLf#">
		<cfif NOT isDefined("bg") OR bg EQ "grayBg">
			<cfset bg="whiteBg">
		<cfelse>
			<cfset bg="grayBg">
		</cfif>
	
		<cfoutput>
			<tr class="#bg#">
			<cfloop list="#run#" index="col" delimiters="#chr(9)#">
				<td>#col#</td>
			</cfloop>
			</tr>
		</cfoutput>
	</cfloop>
	</table>
<cfelse>
	You have apparently never been running.
</cfif>

</body>
</html>

One-dimensional Arrays

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.

Creating Arrays

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.

<cfset beatles = ArrayNew(1)> <cfset beatles[1] = "John"> <cfset beatles[2] = "Paul"> <cfset beatles[3] = "George"> <cfset beatles[4] = "Ringo">

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

Reading from arrays is just a matter of pointing to a specific index of an array.

<cfoutput>#beatles[3]#</cfoutput> <!---outputs George to the browser--->

Looping through Arrays

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.

Code Sample:

ListsAndArrays/Demos/Arrays.cfm
<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[3]#</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.

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.

Array Functions
Function Description
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.

Two-dimensional Arrays

ColdFusion supports two-dimensional arrays, which are similar to tables or grids. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. For example, a two-dimensional array called rockbands could contain the names of the bands and some of the songs that they sing. Below is a grid that represents such a two-dimensional array.

Rockband Song1 Song2 Song3
Beatles Love Me Do Hey Jude Helter Skelter
Rolling Stones Waiting on a Friend Angie Yesterday's Papers
Eagles Life in the Fast Lane Hotel California Best of My Love

The following code sample shows how this two-dimensional array is created. Note that the header row is not included.

Code Sample:

ListsAndArrays/Demos/Arrays-2Dim-create.cfm
<html>
<head>
<title>Rockbands</title>
</head>

<body>
<h1>Rockbands</h1>
<cfset rockbands=ArrayNew(2)>
<cfset rockbands[1][1]="Beatles">
<cfset rockbands[1][2]="Love Me Do">
<cfset rockbands[1][3]="Hey Jude">
<cfset rockbands[1][4]="Helter Skelter">

<cfset rockbands[2][1]="Rolling Stones">
<cfset rockbands[2][2]="Waiting on a Friend">
<cfset rockbands[2][3]="Angie">
<cfset rockbands[2][4]="Yesterday├é’s Papers">

<cfset rockbands[3][1]="Eagles">
<cfset rockbands[3][2]="Life in the Fast Lane">
<cfset rockbands[3][3]="Hotel California">
<cfset rockbands[3][4]="Best of My Love">

</body>
</html>

Reading from Two-dimensional Arrays

To read an element from a two-dimensional array, you must first identify the index of the "row" and then identify the index of the "column." For example, the song "Angie" is in row 2, column 3, so it is identified as rockbands[2][3].

Looping through Two-dimensional Arrays

To loop through a two-dimensional array, you need to nest one loop inside of another. The following code will create an HTML table from our two-dimensional array.

Code Sample:

ListsAndArrays/Demos/Arrays-2Dim-read.cfm
---- C O D E   O M I T T E D ----
<table border="1">
	<cfloop from="1" to="#ArrayLen(rockbands)#" index="i">
	<tr>
		<cfoutput>
		<cfloop from="1" to="#ArrayLen(rockbands[i])#" index="j">
			<td>#rockbands[i][j]#</td>
		</cfloop>
		</cfoutput>
	</tr>
	</cfloop>
</table>

</body>
</html>