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">
<cftry>
	<cfset foo = arr[2]>
	<cfoutput>Something exists at position 2.</cfoutput>
	<cfcatch>
		<cfoutput>Something does NOT exist at position 2.</cfoutput>
	</cfcatch>
</cftry>

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.

Categories

Data Structures

Comments

comments powered by Disqus