Adobe ColdFusion 8

Testing for a variable's existence

Before relying on a variable's existence in an application page, you can test to see if it exists by using the IsDefined function. To check whether a specific key exists in a structure, use the StructKeyExists function.

For example, if you submit a form with an unsettled check box, the action page does not get a variable for the check box. The following example from a form action page makes sure the Contractor check box Form variable exists before using it:

<cfif IsDefined("Form.Contractor")>
    <cfoutput>Contractor: #Form.Contractor#</cfoutput>
    </cfif>

You must always enclose the argument passed to the IsDefined function in double-quotation marks. For more information on the IsDefined function, see the CFML Reference.

If you attempt to evaluate a variable that you did not define, ColdFusion cannot process the page and displays an error message. To help diagnose such problems, turn on debugging in the ColdFusion Administrator or use the debugger in your editor. The Administrator debugging information shows which variables are being passed to your application pages.

Variable existence considerations

If a variable is part of a scope that is available as a structure, you might get a minor performance increase by testing the variable's existence using the StructKeyExists function instead of the IsDefined function.

You can also determine which Form variables exist by inspecting the contents of the Form.fieldnames built-in variable. This variable contains a list of all the fields submitted by the form. Remember, however, that form text fields are always submitted to the action page, and might contain an empty string if the user did not enter data.

The IsDefined function always returns False if you specify an array or structure element using bracket notation. For example, IsDefined("myArray[3]") always returns False, even if the array element myArray[3] has a value. To check for the existence of an array element, use cftry, as in the following example:

<cfset items=ArrayNew(2)>
<cfset items[1][1] = "Dog">
<cfset items[2][2] = "Cat">
<cftry>
  <cfset temp=items[1][2]>
<cfcatch type="any">
<  cfoutput>Items[1][2] does not exist</cfoutput>
</cfcatch>
</cftry>