ColdFusion Ordered Struct


As most readers probably already know, in ColdFusion, structs are associatively keyed storage structures similar to an array but where you get to use a string to key an entry rather than only a sequential number.

PHP only has array() which acts both like ColdFusion’s array and struct both. You can numerically key arrays or associatively key them, or both. One of the reasons it can get away with this is that it preserves the insert order. So if you do:


The output will be the values in the same order they were put into the structure. If you do the same thing in ColdFusion, you’ll get it back in a seemingly random order (or depending on the version some times you’ll get back in alphabetical order):

Instead if you need to preserve insert order, you can use a similar Java object from ColdFusion:

You can treat this like a struct in every way, including <cfdump>ing it (though cfdump will not show you the insert order for some reason). As you iterate over it, the contents will always come back in the same order they were inserted.

It’s important to note that LinkedHashMap keys are also case-sensitive while ColdFusion Struct keys are case insensitive. This may cause undesired results as you might have two keys that you believe are the same but differ in case; this may cause collisions when working with other objects that are not case sensitive.

, ,

  1. #1 by Eric Wilkinson at February 24th, 2010

    Great post! I use coldfusion structs a lot and have always been baffled by the seemingly random ordering. Thanks!

(will not be published)