Using structKeyExists Rather Than isDefined

If you have ever tried using the isDefined function like this:

<cfif isDefined("url['foo']")>

Then you have probably seen this error:

Parameter 1 of function IsDefined, which is now “url[‘foo’]”, must be a syntactically valid variable name.

In situations where you either have to use bracketed syntax, or simply prefer it, try using the structKeyExists function instead, like this:

<cfif structKeyExists(url, "foo")>

Since variable scopes are actually structs, the above syntax works with all scopes exactly like the isDefined function would.

2 Responses to Using structKeyExists Rather Than isDefined

  1. Christian, ColdFusion data structures (the url, form, cookie & session scopes to name a few) are often underutilized.StructKeyExists is one example of how useful Structure functions are for manipulating ColdFusion data structures, another good example is to take advantage of StructIsEmpty if you’re working self posting forms.Instead of using IsDefined to test for the existence of a specific form variable name it would be more flexible to just to use this:<cfif not StructIsEmpty(form)>Andrew

  2. You’re generally better off using structKeyExists() than isDefined() whenever you can. Since it only looks in the struct (or scope) for the key, it will be faster than isDefined() which searches all scopes (because of CF5 compatibility: foo.bar could be a variable called foo.bar as well as a struct called foo with a key called bar).For unqualified variables, use the appropriate scope:structKeyExists(variables,”foo”) vs isDefined(“foo”)