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 />

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:

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

This question was written by Charlie Griefer
It was last updated on January 10, 2006.


Data Structures


comments powered by Disqus