Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check for existing array element

Arrays

Check for existing array element

by  TruthInSatire  Posted    (Edited  )
The built in function isDefined() can not test arrays. Attempting a test will produce an error.

isdefined("myArray[1]")
produces
[quote error]
Parameter 1 of function IsDefined, which is now "myArray[1]", must be a syntactically valid variable name.
[/quote]

In order to test for the existance of an array element this UDF should do the trick.

USE: isArrayElementDefined("myArray[element]")
(This function also works for multi-dimensional arrays)
Code:
[b]<cfscript>[/b]
    [color gray]//define the function[/color]
    [b]function isArrayElementDefined(arrayName){[/b]
          [color gray]//use try{} to attempt using the array element[/color]
          [b]try{[/b]
            [color gray]//use the array element and return true[/color]
            [b]testVar = evaluate(arrayName);
            return true;[/b]
          [color gray]//if using it causes an error catch it and return false[/color]
          [b]}catch(any test){
            return false;
        }
    }
</cfscript>[/b]

EXAMPLE:
Code:
<cfset myArray = arrayNew(1)>
<cfset myArray[1] = "bob">
<cfset myArray[3] = "joe">
<cfoutput>
<cfloop from = "1" to = "3" index = "place">
#isArrayElementDefined("myArray[#place#]")#
</cfloop>
</cfoutput>
OUTPUT: true false true
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top