Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

How do you loop over the values in a structure?

A structure is a complex object that is comprised of key-value pairs.

Let's say we have a structure that represents/describes a person. Keys are 'Name', 'Address', and 'PhoneNumber'...with corresponding values 'Harvey', '123 Main Street', and '555-1212'.

CF's <cfloop> tag provides us with a "collection" loop that is can loop over a structure.

<cfloop collection="#myStructure#" item="key">
#key#: #myStructure[key]#<br />
</cfloop>

The "collection" attribute is the name of your structure (in # signs so CF knows to evaulate it).

The "item" attribute is simply a variable to represent the key of your struct for each iteration. For this reason you'll often see it represented as the variable "key", but it could just as easily have been "i", "x", or "foo".

The output of the loop above would, for each iteration, output the key alone ('Name', 'Address', 'PhoneNumber'), and then the value of that key in the structure ('Harvey', '123 Main Street', '555-1212').

If you prefer <cfscript>, you can use a for-in loop to loop over a structure:

<cfscript>
   for (key in myStruct) {
      writeOutput(key & ": " & myStruct[key] & "<br />");
   }
</cfscript>


This question was written by Charlie Griefer.
It was last updated on January 10, 2006 at 8:14:47 AM EST.

CFML Referenced

<cfscript>
<cfloop>

Categories

Data Structures

Comments

Comment made by lisa on December 14, 2007 at 10:56 AM
How do you use cfloop for repeat form validation, where the form fields are very similar ie name1, name2 name3 etc