Search code examples
coldfusionlucee

How to check for last item when looping through a structure in ColdFusion?


I want to loop over a structure and output something for all items except the last one. For arrays this can easily be done by checking whether the current index is the last one, though how to do it for structures?

Example code:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <!--- Here should be the conditional output --->
</cfloop>
</cfoutput>

Solution

  • Just increment your own "index" as you loop:

    <cfscript>
    myStruct = {
      item1 = "foo",
      item2 = "bar",
      item3 = "baz"
    };
    totalItems = StructCount( myStruct );
    thisItemNumber = 1;
    </cfscript>
    
    <cfoutput>
    <cfloop collection="#myStruct#" item="item">
      #myStruct[item]#
      <cfset thisIsNotTheLastItem = ( thisItemNumber LT totalItems )>
        <cfif thisIsNotTheLastItem>
            is not the last item<br/>
        </cfif>
        <cfset thisItemNumber++>
    </cfloop>
    </cfoutput>
    

    EDIT: Here's an alternative using an array

    <cfscript>
    myStruct = {
      item1 = "foo",
      item2 = "bar",
      item3 = "baz"
    };
    totalItems = StructCount( myStruct );
    keys = StructKeyArray( myStruct );
    lastItem = myStruct[ keys[ totalItems ] ];
    </cfscript>
    <cfoutput>
    <cfloop array="#keys#" item="key">
        #myStruct[ key ]#
        <cfif myStruct[ key ] IS NOT lastItem>
            is not the last item<br/>
        </cfif>
    </cfloop>
    </cfoutput>