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 entry exists in an array, use the ArrayIsDefined 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 quotation marks. For more information on the IsDefined function, see the CFML Reference.

To test whether an element exists in an array before you display its value, use a format such as the following:

</cfoutput> 
    <cfloop index="i" from="1" to="#Arraylen(myArray)#"> 
        <cfif ArrayIsDefined(myArray, i)> 
            #i#: #myArray[i]#<br> 
        </cfif> 
    </cfloop> 
</cfoutput>

Notice that in the ArrayIsDefined function, unlike the IsDefined function, you do not surround the variable name in quotation marks.

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 can contain an empty string if the user did not enter data.