Looping Over Arrays in ColdFusion 9.01 (CFScript)

Posted: February 14, 2012 in ColdFusion
Tags: , ,

This is pretty much a “note to self”… but in ColdFusion 9.01 you can now loop over arrays using the  for – in loop while in cfscript.

Syntax is:

for(item in array) {
  1. You can also var scope ‘item’ inside the loop which saves you from having to do it elsewhere.

    For example:

    for( var item in array ) {

    instead of:

    var item = “”;
    for( item in array ) {

  2. Robert says:

    Looping in CF is still a complete mess though.

    Looping over a collection, be it list, struct, array or otherwise should all conform to a standard syntax.

    I find myself often wrapping collections up in my own iterator objects so if I switch the implementation of a collection from array to struct looping over the collection can still be done with the same syntax.


    • Mike Klostermeyer says:

      When looping in tags you can also use the <cfloop array=""…syntax in the same manner.

      Unfortunately, when you loop this way you can't tell which iteration of the loop you are on without incrementing a separate variable within the code. Granted, you don't always need to know which iteration you are on, but it's ugly when you do.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s