The following sections describe how to use ColdFusion functions to find information about structures and their keys.
To find out if a given value represents a structure, use the IsStruct
function, as follows:
IsStruct(variable
)
This function returns True if variable is a ColdFusion structure. (It also returns True if variable is a Java object that implements the java.util.Map interface.)
Structures are not indexed numerically, so to find out how many name-value pairs exist in a structure, use the StructCount
function, as in the following example:
StructCount(employee)
To discover whether a specific Structure contains data, use the StructIsEmpty
function, as follows:
StructIsEmpty(structure_name
)
This function returns True if the structure is empty, and False if it contains data.
To determine whether a specific key exists in a structure, use the StructKeyExists
function, as follows:
StructKeyExists(structure_name
,"key_name"
)
Do not put the name of the structure in quotation marks, but you do put the key name in quotation marks. For example, the following code displays the value of the MyStruct.MyKey only if it exists:
<cfif StructKeyExists(myStruct, "myKey")> <cfoutput> #mystruct.myKey#</cfoutput><br> </cfif>
You can use the StructKeyExists
function to dynamically test for keys by using a variable to represent the key name. In this case, you do not put the variable in quotation marks. For example, the following code loops through the records of the GetEmployees query and tests the myStruct structure for a key that matches the query's LastName field. If ColdFusion finds a matching key, it displays the Last Name from the query and the corresponding entry in the structure.
<cfloop query="GetEmployees"> <cfif StructKeyExists(myStruct, LastName)> <cfoutput>#LastName#: #mystruct[LastName]#</cfoutput><br> </cfif> </cfloop>
If the name of the key is known in advance, you can also use the ColdFusion IsDefined
function, as follows:
IsDefined("structure_name.key
")>
However, if the key is dynamic, or contains special characters, you must use the StructKeyExists
function.
Note: Using StructKeyExists
to test for the existence of a structure entry is more efficient than using IsDefined
. ColdFusion scopes are available as structures and you can improve efficiency by using StructKeyExists
to test for the existence of variables.
To get a list of the keys in a CFML structure, you use the StructKeyList
function, as follows:
<cfset temp=StructKeyList(structure_name
, [delimiter
] )>
You can specify any character as the delimiter; the default is a comma.
Use the StructKeyArray
function to returns an array of keys in a structure, as follows:
<cfset temp=StructKeyArray(structure_name
)>
Note: The StructKeyList
and StructKeyArray
functions do not return keys in any particular order. Use the ListSort
or ArraySort
functions to sort the results.