We'll start by setting up a structure using . (dot) notation:
<cfscript> loginInfo = structNew(); loginInfo.username = "will"; loginInfo.password = "somePassword"; loginInfo.isAdmin = true; </cfscript>Produces this:
| struct | |
|---|---|
| ISADMIN | true |
| PASSWORD | somePassword |
| USERNAME | will |
Now, using bracketed notation:
<cfscript> loginInfo = structNew(); loginInfo["username"] = "Will"; loginInfo["password"] = "somePassword"; loginInfo["isAdmin"] = "true"; </cfscript>
Yields the same as above:
| struct | |
|---|---|
| isAdmin | true |
| password | somePassword |
| username | Will |
Why is bracketed better? Because it allows us to set dynamic variable names. This can be quite handy, especially when dealing with forms and form values. Here's a simple variable assignment to the variables scope.
<cfloop from="1" to="3" index="thisNum"> <cfset variables["Will" & thisNum] = "Da man!" & thisNum> </cfloop>Da man!1
Da man!2
Da man!3
A little more complex example, showing a dynamic structure:
<cfscript>
for(i = 1; i lte 5; i = i + 1){
loginInfo[i] = structNew();
loginInfo[i]["username"] = "Will";
loginInfo[i]["password"] = "somePassword";
loginInfo[i]["isAdmin"] = "true";
writeOutput(loginInfo[i].username & "<br>" & loginInfo[i].password & "<br>" & loginInfo[i].isAdmin & "<br><br>");
}
</cfscript>
Produces this:
WillsomePassword
true
Will
somePassword
true
Will
somePassword
true
Will
somePassword
true
Will
somePassword
true
| struct | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| 1 |
|
||||||||
| 2 |
|
||||||||
| 3 |
|
||||||||
| 4 |
|
||||||||
| 5 |
|
||||||||
| isAdmin | true | ||||||||
| password | somePassword | ||||||||
| username | Will | ||||||||
To learn more about ColdFusion's built-in Structure functions, visit this page