How do you determine if an array position exists?

ColdFusion does not have any built in function to determine if an array position is defined. The simplest way is to use ColdFusion's built-in exception handling. The following code will check for the second position in an array:

<cfset arr = arrayNew(1)>
<cfset arr[1] = "Jacob">
<cfset arr[3] = "Lynn">
<cfset arr[5] = "Noah">
	<cfset foo = arr[2]>
	<cfoutput>Something exists at position 2.</cfoutput>
		<cfoutput>Something does NOT exist at position 2.</cfoutput>

Another option is to use the arrayToList() function. In an array with empty positions, this will return a list with empty values. However, ColdFusion's list functions will not correctly tell you if a position is empty.

For a simpler version of the code above, the user-defined function, arrayDefinedAt(), may be used.

This question was written by Raymond Camden
It was last updated on January 12, 2006.


Data Structures


comments powered by Disqus