Dealing with empty elements

an article added by: Albert Niftiger at 04012008


In: Root » Computers and technology » Programming » Dealing with empty elements

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

Empty elements are elements within a list that contain no value. To see how to deal with them, take the following list:

<cfset myList = “apple,pear,,orange,banana,”>

How many elements are in myList? You’d think six, but ColdFusion’s list functions see only four because ColdFusion counts empty list elements—such as the one between pear and orange and the empty element at the end of the list—as nonexistent. If you need an empty element, you must put spaces in the list, as in the following example:

<cfset myList = “apple,pear, ,orange,banana, “>

A good practice is to avoid empty elements if possible. ColdFusion’s list-processing functions work differently than do the list-processing functions in most other languages and could present a portability issue. What if you suddenly needed to use a semicolon as your list delimiter instead of a comma? You would use ListChangeDelims() as follows:

<cfset myList = ListChangeDelims(myList, “;”, “,”)>

myList now contains “apple;pear;orange;banana”. The interesting thing about ListChangeDelims() is that it automatically removes empty elements. Take, for example, the following list:

<cfset myList = “apple,pear,,orange,banana,”>

ListChangeDelims() would return “apple;pear;orange;banana”. Using ListChangeDelims(), therefore, is also a good way to remove empty elements even if you’re not changing delimiters, as follows:

<cfset myList = ListChangeDelims(myList, “,”, “,”)>

The lists that we’ve been using in the preceding parts have all been in random order. If you need items in a list to be in a particular order, you can use ListSort(), as follows:

<cfset myList = ListSort(myList, “text”, “asc”)>

After calling ListSort(), myList would contain the following: apple,banana,orange,pear As does ListChangeDelims(), ListSort() removes empty elements. The second argument to ListSort() is the type of sort to perform. This argument can take any of the following three values:

Numeric: Sorts the list numerically. If any list element cannot be converted to a number, ColdFusion throws an error.

Text: Sorts the list alphabetically but is case sensitive. Try calling ListSort() on the following list:

Pear, apple, Banana, peach

This call would return the following:

Banana, Pear, apple, peach

A case-sensitive sort always returns uppercase letters before lowercase letters; as such, any words in all capital letters would sort before any initial-capped words. Just the fact that a letter is uppercase is enough to guarantee that the letter will come before any lowercase letter.

Textnocase: Sorts the list alphabetically, ignoring case. Calling ListSort() on the preceding list would return the following:

apple, Banana, peach, Pear

The third argument to ListSort() can be asc or desc depending on whether you want an ascending or descending sort. Suppose that you had the following list:

pear, orange, lemon, citron

But suppose, too, that you wanted to use it in a query such as the following:

SELECT *
   FROM Fruit
   WHERE FruitName IN (‘pear’,’orange’,’lemon’,’citron’)

You couldn’t just use it as follows:

SELECT *
   FROM Fruit
   WHERE FruitName IN (#myList#)

That’s because myList doesn’t have single quotes around its items, and the database would throw an error when it tried to execute the query. Before using myList in a query, you must qualify the list elements by surrounding them with single quotes. ColdFusion offers a function named ListQualify() to do just that, as the following example shows:

SELECT *
   FROM Fruit
   WHERE FruitName IN (#ListQualify(myList, “‘“)#)

The second attribute describes the qualifier—in this case, a single quote. Arrays, as do lists, store multiple values under a single name and have a library of functions built around them. Unlike lists, however, arrays store data in separate compartments and not just as a delimited string. Where lists are simple variables (that is, they are just simple strings with formally defined delimiters), arrays are complex variables, meaning that they may contain more than a single value and create programmatically addressable compartments for those values. Unlike a list, which is a simple string variable, an array is a special type of object that is created by calling a function named ArrayNew() , as follows:

<cfset myArray = ArrayNew(1)>

ArrayNew() creates a new, one-dimensional array object and assigns it to the variable myArray. An array can have up to three dimensions. A one-dimensional array creates a stack of elements. A two-dimensional array is like a grid of elements. As you can probably guess, a three-dimensional array is like a cube of elements. Multidimensional arrays are rarely useful unless you’re doing matrix mathematics (which no one should be doing in ColdFusion anyway). You refer to an array element through positional notation, as follows:

<cfoutput>#myArray[2]#</cfoutput>

This snippet outputs the second element in the array. The index of an array (the number between the square brackets) can also be a variable containing a numeric value. Mentioning that arrays begin counting at 1 may seem redundant, but in most computer languages —such as JavaScript—arrays begin at element 0. Keep this fact in mind if you ever populate a JavaScript array by using ColdFusion array elements. To add an element to the end of an array, use ArrayAppend(), as follows:

<cfset myArray = ArrayNew(1)>
   <cfset ArrayAppend(myArray, “apple”)>

Notice the difference between ListAppend() and ArrayAppend() in the following examples:

<cfset myList = ListAppend(myList, “apple”)>
   <cfset ArrayAppend(myArray, “apple”)>

ListAppend() does not modify the original list; instead, it returns the original list with the new element appended. ArrayAppend(), however, modifies the original array. The only thing that ArrayAppend() ever returns is TRUE, so you don’t even need to store the return value. ColdFusion also has an ArrayPrepend() function, as follows:

<cfset ArrayPrepend(myArray, “peach”)>

You can also insert a new array element between already existing elements. After calling ArrayNew() and ArrayAppend() earlier in this article, for example, myArray looks as follows:

1: peach
 2: apple

You can insert a new element between the two by using ArrayInsertAt() as follows:

<cfset ArrayInsertAt(myArray, 2, “lemon”)>

myArray now has a new element between peach and apple, as the following shows:

1: peach
   2: lemon
 3: apple

You can also create array elements by directly assigning a value to a position, as follows:

<cfset myArray[4] = “blueberry”>

Now myArray has a fourth element, as you can see in the following result:

1: peach
   2: lemon
   3: apple
 4: blueberry

You can also skip elements, as follows:

<cfset myArray[6] = “pomegranate”>

This code leads to another array element in myArray, as shown in the following:

1: peach
   2: lemon
   3: apple
   4: blueberry
   5: <no element>
   6: pomegranate

Notice that no element lies at position 5 in myArray. This result doesn’t mean that the element is blank; it simply doesn’t exist. The difference between blank and nonexistent is sometimes hard to understand, but it boils down to this: Attempting to use myArray[5] when the fifth element doesn’t exist will throw an error, whereas if the fifth element is blank, myArray[5] will return a blank string. You can delete an item from an array by using ArrayDeleteAt(), as follows:

<cfset ArrayDeleteAt(myArray, 6)>

That line deletes the sixth item from the array that we describe in the preceding part. Notice that the new length of the array is now five, even though the fifth element is undefined. If you need to quickly delete all the elements of an array, use ArrayClear(), as follows:

<cfset ArrayClear(myArray)>

After you call ArrayClear(), the array has no elements remaining. Following is an easy way to find out whether an array has any elements:

<cfif ArrayIsEmpty(myArray)>

This array is empty.

<cfelse>

This array has at least one element.

</cfif>

To find the specific number of elements in an array, use ArrayLen(), as follows:

<cfset numElements = ArrayLen(myArray)>

Both ArrayLen() and ArrayIsEmpty() count undefined elements, so be careful because you usually don’t account for undefined elements in the rest of your code. Finding an item in a list is a simple matter of calling ListFind() or ListFindNoCase(). You have, however, no array-based equivalent to ListFind(). Instead, you must use a loop, as follows:

<cfloop from=”1” to=”#ArrayLen(myArray)#” index=”i”>
   <cfif myArray[i] EQ “apple”>
   <cfbreak>
   </cfif>
   </cfloop>

After this loop is finished, i contains the array index that contains “apple”—in this case, 3. An aggregate function takes an array containing numbers as an argument and returns a single value representing some characteristic of those numbers. ColdFusion arrays have four aggregate functions, and they are all shown in the code. Note that the aggregate functions are shown in bold, and that each of them take a single argument: the array containing the data to be aggregated.

<cfset myNumericArray = ArrayNew(1)>
   <cfset myNumericArray[1] = 1>
   <cfset myNumericArray[2] = 7.5>
   <cfset myNumericArray[3] = 5>
   <cfset myNumericArray[4] = 8>
 <cfset myNumericArray[5] = 2>
<cfset myNumericArray[6] = 10>
   <cfset myNumericArray[7] = 0>
   <cfset myNumericArray[8] = 1.5>
   <pre>
   <cfoutput>
   Sum of array elements: #ArraySum(myNumericArray)#
   Smallest array element: #ArrayMin(myNumericArray)#
   Largest array element: #ArrayMax(myNumericArray)#
   Average of array elements: #ArrayAvg(myNumericArray)#
   </cfoutput>
 </pre>

If any elements in an array cannot be converted to a number, ColdFusion throws an error if you attempt to use an aggregate function. Another feature arrays have that lists don’t is the capability to easily swap elements. Suppose that myArray looks as follows:

1: peach
   2: lemon
   3: apple
 4: blueberry

To swap the first and third elements, you would use ArraySwap(), as follows:

<cfset ArraySwap(myArray, 1, 3)>

myArray would then look as follows:

1: apple
   2: lemon
   3: peach
   4: blueberry

As with lists, you can easily sort an array by using ArraySort(), as follows:

<cfset ArraySort(myArray, “text”, “asc”)>

After you call ArraySort(), myArray would contain the following:

1: apple
   2: blueberry
   3: lemon
 4: peach

If any undefined elements are in the array as you attempt to use ArraySort(), ColdFusion throws an error. As for ListSort(), the second argument to ArraySort() describes the type of sort that you want to perform. This argument can take the following three values:

Numeric: Sorts the array numerically. If any array element cannot be converted to a number, ColdFusion throws an error.

Text: Sorts the array alphabetically but is case sensitive. Suppose that you call ArraySort() on the following array:

1: Pear
   2: blueberry
   3: Apple
 4: peach

This call would return the following result:

1: Apple
   2: Pear
   3: blueberry
 4: peach

Textnocase: Sorts the array alphabetically, ignoring case. Calling ArraySort() on the preceding array would return the following result:

1: Apple
   2: blueberry
   3: peach
   4: Pear

The third argument to ArraySort() can be asc or desc, depending on whether you want an ascending or descending sort. Whenever you add an element to an array, you’re allocating memory in ColdFusion Server. Sometimes, however, not enough memory is available in the array’s current location; if this happens, the entire array must be reallocated and moved. This operation can be very costly in terms of CPU time and memory usage if you have more than a few elements in your array. For efficiency’s sake, if you know the number of elements that an array is to contain before you start adding them, you can use ArrayResize() to pre-allocate the space that you need, as follows:

<cfset ArrayResize(myArray, 500)>

For maximum efficiency in your code, call ArrayResize() immediately after ArrayNew(). Lists offer certain features that arrays don’t, such as the capability to easily find an element. But you can also do some things easily with arrays that are difficult with lists, such as finding an average. For this reason, you often find yourself using a list when you need the functionality of an array and vice-versa. To get around this conundrum, you can convert a list to an array—or an array to a list—by using the ListToArray() and ArrayToList() functions, as follows:

<cfset myNewArray = ListToArray(myList)>
   <cfset myNewList = ArrayToList(myArray)>

These functions can be memory-intensive for large lists and arrays, so use these two functions only if you really need them. If your array contains complex values, ArrayToList() throws an error. Also note that when you convert a list to an array using ListToArray (), ColdFusion removes empty elements from the array, but the converse is not true. ArrayToList () preserves any empty elements in the array, possibly throwing off code that requires both to be synchronized.

After you know how to use lists and arrays, you need to decide what to do with them. Both expose much of the same functionality, so which is better for what purpose? Think of lists more as multivalued strings than as actual complex data types. Lists are good for storing sets of data in which you may need to find items quickly. Arrays are better suited for highly ordered sets of data, especially if you must coordinate the contents of two arrays. Remember, too, that arrays are the only effective way to use aggregate functions. You must, however, use lists if you must store data in a Client variable. You cannot use an array for this purpose, because Client variables can’t store complex data. You can, however, convert the array to a list and then store the list in a Client variable. As we mentioned earlier in this article, if you can’t guarantee that any particular delimiter is going to appear in the list items, you should use an array to store the data instead. An array separates its values from one another by keeping each value in its own compartment rather than stringing them all together. Arrays and lists are powerful tools if applied correctly. Each has its pros and cons, but in most cases, you can convert one to the other so that its specific set of functions can be used. In this article you learned how to effectively use both arrays and lists, and also how to choose between the two. Lists are simple variables that contain multiple values separated by delimiters, and they are useful where you don’t need use aggregate functions on their values. Arrays are complex variables that contain multiple values in programmatically addressable compartments, and they are useful where aggregate functions are needed.

legal disclaimer

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

related articles

1. Building the company add action template
In this article, you create the template that puts your form data into the database. Create a file named CompanyAddAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”InsertCompany” datasource=”#Request.MainDSN#”> INSERT INTO Company( CompanyName, Address, City, State, ZipCode, Comments ) VALUES ( ‘#Trim(Form.CompanyName)#’, ‘#Trim(Form.Address)#’, ...

2. Modifying a Company in the Database
The data that CFQUERY requests from the database comes back in a result set, and the Name attribute tells ColdFusion what that result set is to be named. The SQL statement consists of three clauses: SELECT, FROM, and ORDER BY. SELECT tells the database which columns to retrieve from the database; FROM tells the database which table to retrieve those columns from; and ORDER BY tells the database how to sort the results. The result set returned from CFQUERY contains multiple rows of data, and each row has multiple columns. It would ...

3. Building the company edit action template
The code in CompanyEditAction.cfm is like the code in CompanyAddAction.cfm, but the edit action updates rather than inserts. Create a file named CompanyEditAction.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <cfquery name=”UpdateCompany” datasource=”#Request.MainDSN#”> UPDATE Company SET CompanyName = ‘#Trim(Form.CompanyName)#’, Address = ‘#Trim(Form.Address)#’, City = ‘#Trim(Form.City)...

4. Adding a New Employee to the Database
The CFQUERY in CompanyDeleteAction.cfm uses a DELETE statement with two SQL clauses: DELETE and WHERE. DELETE tells the database the table from which to delete a record, and WHERE tells the database which record to delete. You can watch the company delete process in action. Point your Web browser to http://<yourserver>/CFMXBible/Ch02/CompanyGetDeleteForm.cfm and enter a CompanyID. (To get a valid ID, go to the company list and pick a number from the ID column.) Click Submit to see the chosen company’s informatio...

5. Modifying an Employee in the Database
The DateFormat() function around the DateOfBirth column in the codereturns the employee’s birth date reformatted according to a display mask. DateOfBirth normally comes back from the database in the following format: 2002-01-01 00:00:00.0 That format is not very user-friendly. Calling DateFormat() with a mask of “mm/dd/yyyy” returns the date as follows: 01/01/2002 This version is, of course, more natural and easy to read. The same is true for the employee edit process...

6. Removing an Employee From the Database
The user must have the capability to remove employees from the database. The employee delete process is a simple combination of techniques that you have already learned, such as retrieving a record from the database, displaying that record in a template, and so on. The first page in this process is nearly identical to the employee get edit form. Create a file named EmployeeGetDeleteForm.cfm inside the Ch02 directory, type the code into the file’s editing window, and save the file. <html> <head> <ti...

7. Making direct links to the forms
Say that you want to modify or delete a company. Right now, you need to remember the company’s ID, go back to the launch pad, click Company Edit, and enter the company ID, all just to get to the edit form. Wouldn’t you rather click a company in the list and go directly to the edit form? ... <table> <tr> <td><b>ID</b></td> <td><b>Name</b></td> <td><b>Address</b></td> <td><b>City</b></t...