Utility Function: ArrayElementIsDefined()

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>

 
Comments are not allowed for this entry.
Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me on LinkedIn.