Search code examples
arrayscoldfusioncfloop

How to loop through array and output two elements at the same time not repeating previous index?


I have an array of numbers, while looping through array I want to output two elements at the time. Here is my array:

<cfset myArray = [74539,1500285,1334095,1500293,1334096,1500294,1334098,1500295,1334109,1500296]>

Here is my loop:

<cfoutput>
    <cfloop from="1" to="#arraylen(myArray)#" index="a">
        <cfset currAssignID = firstAssignList[a]>
        <cfset nextAssignID = firstAssignList[a+1]>
        #currAssignID# - #nextAssignID#<br>
    </cfloop>
</cfoutput>

Code above will produce this output:

74539 - 1500285
1500285 - 1334095
1334095 - 1500293
1500293 - 1334096
1334096 - 1500294
1500294 - 1334098

As you can see my code is outputting previous number every time, I would like to see this:

74539 - 1500285
1334095 - 1500293
1334096 - 1500294
1334098 - 1500295
1334109 - 1500296

If anyone knows where my code is breaking please let me know. Thank you.


Solution

  • You can use the step attribute on the loop to specify the increment that the loop goes through the elements. As you want to output them in pairs you can set step="2". This will skip every other element.

    <cfset myArray = [74539,1500285,1334095,1500293,1334096,1500294,1334098,1500295,1334109,1500296,1334110,1500297,1334117,1500298,1334124,1500299,1334138,1500286,1334139,1500287,1334140,1500288,1337768,1500289,1338779,1500290,1338783,1500291,1338801,1500292]>
    
    
    <cfoutput>
        <cfloop step="2" from="1" to="#arraylen(myArray)#" index="a">
            <cfset currAssignID = myArray[a]>
            <cfset nextAssignID = myArray[a+1]>
            #currAssignID# - #nextAssignID#<br>
        </cfloop>
    </cfoutput>
    

    This will give the results:

      74539 - 1500285
      1334095 - 1500293
      1334096 - 1500294
      1334098 - 1500295
      1334109 - 1500296
      1334110 - 1500297
      1334117 - 1500298
      1334124 - 1500299
      ... and so on
    

    You can see an example here - http://trycf.com/gist/32a57dc787ba2756c88b4d1b74e3917c/acf11?theme=monokai