Creating structures

In ColdFusion, you can create structures explicitly by using a function, and then populate the structure using assignment statements or functions, or you can create the structure implicitly by using an assignment statement.

Creating structures using functions

You can create structures by assigning a variable name to the structure with the StructNew function as follows:

<cfscript>
    structName=StructNew();
</cfscript>

For example, to create a structure named departments, use the following syntax:

<cfscript>
    departments=StructNew();
</cfscript>

This statement creates an empty structure to which you can add data.

Support for ordered structs

In the 2016 release of ColdFusion, you can create a struct that maintains insertion order.

When you loop over the struct using StructNew(“Ordered”), keys are fetched according to the insertion order.

For example,

<cfscript>
departments = structNew("Ordered");
 /** On iterating this struct, you get the values in insertion order, which is the way you inserted the values. **/
 /** Create a structure and set its contents. **/
     
     departments.John = "Sales";
     departments.Tom = "Finance";
     departments.Mike = "Education";
     departments.Andrew = "Marketing";
     
 /** Build a table to display the contents **/
     
</cfscript>
<cfoutput >
<table cellpadding="2" cellspacing="2">
    <tr>
        <td><b>Employee</b></td>
        <td><b>Department</b></td>
    </tr>
<!--- Use cfloop to loop through the departments structure.The item attribute specifies a name for the structure key. --->
   <cfloop collection=#departments# item="person">
        <tr>
            <td>#person#</td>
            <td>#Departments[person]#</td>
        </tr>
    </cfloop>
</table>
</cfoutput>

The code produces the following output:

Employee

Department

John

Sales

Tom

Finance

Mike

Education

Andrew

Marketing

Creating structures implicitly

In the 2016 release of ColdFusion, you can create an empty ordered structure implicitly, as in the following example:

<cfset myStruct = [:]> OR <cfset myStruct = [=]>

The following example shows how to create struct from literal syntax:

departments = [Marketing = "John", Sales : [Executive : "Tom", Assistant = "Mike"]];

You can create an empty structure implicitly, as in the following example:

<cfset myStruct = {}>

You can also create a structure by assigning data to a variable. For example, each of the following lines creates a structure named myStruct with one element, name, that has the value Adobe Systems Incorporated.

<cfscript>
    coInfo=StructNew();
    coInfo.name="Adobe Systems Incorporated";
    coInfo["name"]="Adobe Systems Incorporated";
    coInfo={name="Adobe Systems Incorporated"};
</cfscript>

When you use structure notation to create a structure, as shown in the third example, you can populate multiple structure fields. The following example shows this use:

<cfscript>
    coInfo={name="Adobe Systems Incorporated" industry="software"};
</cfscript>

ColdFusion allows nested implicit creation of structures, arrays, or structures and arrays. For example,

<cfset myStruct = {structKey1 = {innerStructKey1 = "innerStructValue1"}}>

You can use object.property notation on the left side of assignments inside structure notation. For example,

<cfset myStruct={structKey1.innerStructKey1 = "innerStructValue1"}>

You can also use multiple statements, such as the following:

<cfset innerStruct1 = {innerStructKey1 = "innerStructValue1"}>
<cfset myStruct1={structKey1 = innerStruct1}>

You cannot use a dynamic variable when you create a structure implicitly. For example, the following expression generates an error:

<cfset i="coInfo"> 
<cfset "#i#"={name = "Adobe Systems Incorporated"}>

Using implicitly created structures in functions and tags

You can use implicitly created structures directly in functions (including user-defined functions) and tags. For example, the following code dumps an implicitly created structure.

<cfdump var="#{Name ="28 Weeks Later", Time = "7:45 PM"}#">

You can use array notation inside the structure notation, as shown in the following example:

<cfset student = {firstName="Jane", lastName="Janes", grades=[91, 78, 87]}>

Adding and updating structure elements

You add or update a structure element to a structure by assigning the element a value or by using a ColdFusion function. It is simpler and more efficient to use direct assignment.
You can add structure key-value pairs by defining the value of the structure key, as the following example shows:

<cfscript>
       myStruct=StructNew();
       myStruct.key1="A new structure with a new key";
       WriteDump(myStruct);
       myStruct.key2="Now I've added a second key";
       WriteDump(myStruct);
</cfscript>

The following code uses cfset and object.property notation to create a structure element called departments.John, and changes John's department from Sales to Marketing. It then uses associative array notation to change his department to Facilities. Each time the department changes, it displays the results:

<cfset departments=structnew()> 
<cfset departments.John = "Sales"> 
<cfoutput> 
Before the first change, John was in the #departments.John# Department<br> 
</cfoutput> 
<cfset Departments.John = "Marketing"> 
<cfoutput> 
After the first change, John is in the #departments.John# Department<br> 
</cfoutput> 
<cfset Departments["John"] = "Facilities"> 
<cfoutput> 
After the second change, John is in the #departments.John# Department<br> 
</cfoutput>

Getting information about structures and keys

You use ColdFusion functions to find information about structures and their keys.

Getting information about structures

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.

Finding a specific key and its value

To determine whether a specific key exists in a structure, use the StructKeyExists function, as follows:

StructKeyExists(structure_name, "key_name")

Do not place the name of the structure in quotation marks, but you do place the key name in quotation marks.

<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 place 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 theLastName field of the query. 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, 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.

Getting a list of keys in a structure

To get a list of the keys in a CFML structure, you use the StructKeyList function, as follows:

<cfset temp=StructKeyList(structure_name, [delimiter])>

Example of using StructKeyList

<cfscript>
       myStruct=StructNew();
       myStruct.key1="Bugatti";
       myStruct.key2="Lamborghini";
       myStruct.key3="Maserati";
       myStruct.key4="Ferrari";
       myStruct.key5="Aprilia";
       myStruct.key5="Ducati";
       WriteOutput("The input struct is:");
       WriteDump(myStruct);
       WriteOutput("struct has " & StructCount(myStruct) & " keys: " & StructKeyList(myStruct) & "<br/>");
</cfscript>

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.

Copying structures

ColdFusion provides several ways to copy structures and create structure references. The following table lists these methods and describes their uses:

Technique

Use

Duplicate function

Makes a complete copy of the structure. All data is copied from the original structure to the new structure, including the contents of structures, queries, and other objects. As a result changes to one copy of the structure have no effect on the other structure.This function is useful when you want to move a structure completely into a new scope. In particular, if a structure is created in a scope that requires locking (for example, Application), you can duplicate it into a scope that does not require locking (for example, Request), and then delete it in the scope that requires locking.

StructCopy function

Makes a shallow copy of a structure. It creates a structure and copies all simple variable and array values at the top level of the original structure to the new structure. However, it does not make copies of any structures, queries, or other objects that the original structure contains, or of any data inside these objects. Instead, it creates a reference in the new structure to the objects in the original structure. As a result, any change to these objects in one structure also changes the corresponding objects in the copied structure.The Duplicate function replaces this function for most, if not all, purposes.

Variable assignment

Creates an additional reference, or alias, to the structure. Any change to the data using one variable name changes the structure that you access using the other variable name.This technique is useful when you want to add a local variable to another scope or otherwise change the scope of a variable without deleting the variable from the original scope.

Copying a structure

<cfscript>
    myStruct = StructNew();
    myNewStruct = StructNew();
    myStruct.key1 = "The quick brown fox";
    myStruct.key2 = "jumped over the";
    myStruct.key3 = "lazy dog";
    myNewStruct.k1 = "Atlantic";
    myNewStruct.k2 = "Pacific";
    myNewStruct.k3 = "Indian";
    myArray[1]="North Island";
    myArray[2]="South Island";
    myStruct.key4 = myNewStruct;
    // Assign myArray as a key to myNewStruct
    myNewStruct.k4=myArray;
    // Print myStruct
    WriteOutput("The original struct is:");
    WriteDump(myStruct);
    // Copy the structure myStruct into a structure called copiedStruct
    copiedStruct=StructCopy(myStruct);
    // Print copiedStruct
    WriteOutput("The copied struct is:");
    WriteDump(copiedStruct);
</cfscript>

Duplicating a structure

<cfscript>
    myStruct = StructNew();
    myNewStruct = StructNew();
    myStruct.key1 = "The quick brown fox";
    myStruct.key2 = "jumped over the";
    myStruct.key3 = "lazy dog";
    myNewStruct.k1 = "Atlantic";
    myNewStruct.k2 = "Pacific";
    myNewStruct.k3 = "Indian";
    myArray[1]="North Island";
    myArray[2]="South Island";
    myStruct.key4 = myNewStruct;
    // Assign myArray as a key to myNewStruct
    myNewStruct.k4=myArray;
    // Print myStruct
    WriteOutput("The original struct is:");
    WriteDump(myStruct);
    // copy the structure myStruct into a structure called copiedStruct
    copiedStruct=StructCopy(myStruct);
    // Change copiedStruct properties
    copiedStruct.n1="Alien";
    copiedStruct.n2="Predator";
    copiedStruct.n3="Terminator";
    // Create a new struct anotherStruct
    anotherStruct=StructNew();
    anotherStruct.t1="Amazon";
    anotherStruct.t2="Nile";
    anotherStruct.t3="Danube";
    // Assign anotherStruct as a new key to copiedStruct
    copiedStruct.n4=anotherStruct;
    // Print copiedStruct
    WriteOutput("The changed struct,copiedStruct, is:");
    WriteDump(copiedStruct);
    // Create a duplicate version of copiedStruct
    cloneStruct=Duplicate(copiedStruct);
    // Print cloneStruct
    WriteOutput("The new duplicate struct is:");
    WriteDump(cloneStruct);
</cfscript>

Deleting structure elements and structures

To delete a key and its value from a structure, use the StructDelete function, as follows:

StructDelete(structure_name, key [, indicateNotExisting ])

Example of using StructDelete

<cfscript>
       myStruct=StructNew();
       myStruct.item1="JPG";
       myStruct.item2="BMP";
       myStruct.item3="PNG";
       // Print myStruct
       WriteOutput("The input struct is:");
       WriteDump(myStruct);
       // Delete key "item1" from myStruct
       StructDelete(myStruct,"item1");
       // Print updated myStruct
       WriteOutput("The modified struct is:");
       WriteDump(myStruct);
</cfscript>

The indicateNotExisting argument tells the function what to do if the specified key does not exist. By default, the function always returns True. However, if you specify True for the indicateNotExisting argument, the function returns True if the key exists and False if it does not.

You can also use the StructClear function to delete all the data in a structure but keep the structure instance itself, as follows:

StructClear(structure_name)

If you use StructClear to delete a structure that you have copied using the StructCopy function, the specified structure is deleted, but the copy is unaffected. 

If you use StructClear to delete a structure that has multiple references, the function deletes the contents of the structure and all references point to the empty structure, as the following example shows:

Example of using StructClear

<cfscript>
       myStruct=StructNew();
       myStruct.item1="JPG";
       myStruct.item2="BMP";
       myStruct.item3="PNG";
       // Print myStruct
       WriteOutput("The input struct is:");
       WriteDump(myStruct);
       // Create another struct
       myAnotherStruct=StructNew();
       // Copy myStruct to a new structure
       myAnotherStruct=StructCopy(myStruct);
       // Print myAnotherStruct
       WriteOutput("The copied struct is:");
       WriteDump(myAnotherStruct);
       // Delete the structure myAnotherStruct
       StructClear(myAnotherStruct);
       // Print myAnotherStruct after deletion
       WriteOutput("The deleted struct is:");
       WriteDump(myAnotherStruct);
</cfscript>

Looping through structures

You can loop through a structure to output its contents, as the following example shows:

<cfscript>
       myStruct=StructNew();
       myStruct.name1="Jeb";
       myStruct.name2="Bernie";
       myStruct.name3="Hillary";
       myStruct.name4="Donald";
</cfscript>
<cfloop array=#StructSort(myStruct)# index="i" >
       <cfoutput>
             #myStruct[i]#<br/>
       </cfoutput>
</cfloop>

Performing a numeric sort

Perform a numeric sort by setting the sortType attribute to "numeric", as shown below:

<cfscript>
       myStruct=StructNew();
       myStruct.number1=75;
       myStruct.number2=1112;
       myStruct.number3=-674;
       myStruct.number4=12;
       myStruct.number5=3456;
       myStruct.number6=-342;
       myStruct.number7=3.14;
</cfscript>  
<cfloop array=#StructSort(myStruct,"numeric")# index="i" >
     <cfoutput >
            #myStruct[i]#<br/>
     </cfoutput>
</cfloop>

Community contributed help

Some more valid statements:

<cfset myStruct = {structKey1 = {innerStructKey1 = "innerStructValue1"}}>

<cfset myStruct={structKey1.innerStructKey1 = "innerStructValue1"}>

<cfset "#i#"={name = "Adobe Systems Incorporated"}>

You can also use a colon:

<cfset myStruct={structKey1.innerStructKey1 : "innerStructValue1"}>

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy