Utility Function: ArrayElementIsDefined()
- November 27, 2008 5:30 AM
- Utility Function
- Comments (0)
The other day I was trying to be clever and use a multi dimensional array as a kind of look up table for cached results based on two values. For example:
<cfset array = ArrayNew(2) />
<cfif NOT (ArrayIsDefined(array, x) AND NOT ArrayIsDefined(array[x], y))>
<cfset array[x][y] = someFunction(x, y) />
</cfif>
<cfset result = array[x][y] />
And what did I discover? The system bulks and throws an error... apparently even though ArrayIsDefined() is supposed to tell you if values exist in an array, it can't do that until at least 1 value has entered the array.
While I could have just done something like set array[1][1] = 0, it wouldn't have been quite right (what if x and y are 1 for real?), and it didn't sit right with me that ArrayIsDefined() didn't work in this situation. Here is my stand in for ArrayIsDefined().
<cffunction name="ArrayElementIsDefined" output="false" returntype="boolean">
<cfargument name="array" type="array" required="true" />
<cfargument name="index" type="numeric" required="true" />
<cfset var returnValue = false />
<cftry>
<cfset returnValue = ArrayIsDefined(arguments.array, arguments.index) />
<cfcatch type="any">
<!--- Do nothing, the return value is already false --->
</cfcatch>
</cftry>
<cfreturn returnValue />
</cffunction>