Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test to see if a variable exists in a ColdFusion struct?

Tags:

coldfusion

I would like to test:

<cfif Exists(MyStruct["mittens"])>
</cfif>

If the "mittens" key doesn't exist in MyStruct, what will it return? 0, or ""??

What should replace Exists function?

UPDATE

I tried,

<cfif IsDefined(MyStruct.mittens)>

Which also throws the error

Element Mittens is undefined in MyStruct.

like image 705
CVertex Avatar asked Apr 21 '09 06:04

CVertex


People also ask

What is a struct ColdFusion?

ColdFusion structures consist of key-value pairs. Structures let you build a collection of related variables that are grouped under a single name. You can define ColdFusion structures dynamically. You can use structures to reference related values as a unit, rather than individually.

What is Cfparam in ColdFusion?

Tests for a parameter's existence, tests its data type, and, if. a default value is not assigned, optionally provides one.

How do you check null values in ColdFusion?

Use the isNull() method to evaluate for nothingness and use the null keyword to create a null value (ACF 2018+, Lucee 4.1+). In previous versions, use the function call javaCast( "null", "" ) for ACF or in Lucee you can use the nullValue() function. Take note that in Adobe CF 2018+ you must enable the setting.


2 Answers

To test for key existence, I recommend:

<cfif StructKeyExists(MyStruct, "mittens")>

<!--- or --->

<cfset key = "mittens">
<cfif StructKeyExists(MyStruct, key)>

Behind the scenes this calls the containsKey() method of the java.util.map the ColdFusion struct is based on. This is arguably the fastest method of finding out if a key exists.

The alternative is:

<cfif IsDefined("MyStruct.mittens")>

<!--- or --->

<cfset key = "mittens">
<cfif IsDefined("MyStruct.#key#")>

Behind the scenes this calls Eval() on the passed string (or so I believe) and tells you if the result is a variable reference. In comparison this is slower than StructKeyExists(). On the plus side: You can test for a sub-key in a nested structure in one call:

<cfif IsDefined("MyStruct.with.some.deeply.nested.key")>
like image 100
Tomalak Avatar answered Oct 10 '22 19:10

Tomalak


Found the answer here

It's StructKeyExists

like image 40
CVertex Avatar answered Oct 10 '22 21:10

CVertex