Skip to content

Instantly share code, notes, and snippets.

@cocolote
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocolote/567ee767273145eb15ca to your computer and use it in GitHub Desktop.
Save cocolote/567ee767273145eb15ca to your computer and use it in GitHub Desktop.
wild loops

Loops

  • The old for loop

cfloop have step attribute that you can use it to: increment in a different pase or decrement using negative numbers step = "-1" this would decrement 1 by one

<cfloop from="1" to="5" index="i">
    <cfoutput>#i#</cfoutput><br/>
</cfoutput>
  • loop a list

A list is a string delimited by commas. CF adds some properties to it

<cfset myList = 'Jeff,John,Steve,Julliane' />
<cfloop from="1" to="#listlen(myList)#" index="i">
    <cfoutput>#i# #listGetAt(myList, i)#</cfoutput><br/>
</cfoutput>

or like looping through an array

<cfset myList = 'Jeff,John,Steve,Julliane' />
<cfloop list="#myList#" index="item">
    <cfoutput>#itme#</cfoutput><br/>
</cfoutput>

you could determine a different delimiter in the loop to iterate through a list

<cfset myList = "This is a message to test" />
<cfloop list="#myList#" index="word" delimiters=" ">
    <cfoutput>#word#</cfoutput><br/>
</cfloop>
  • Coditional loop

the conditional loops work like a while loope. While the condition is true it would keep executing the code in the middle. In the example I'm iterating through the elements in an array while it has elements.

<cfset myArray = ["Jeff", "John", "Steve", "Julianne"] />
<cfloop conditio="#arrayLen(myArray)#">
    <cfoutput>Current length = #arrayLen(myArray)#</cfoutput><br/>
    <cfset arrayDeleteAt(myArray, 1) />
</cfloop>

Now script time

  • The old plain for loop from java
<cfset myArray = ["Jeff", "Kameron", "Gen", "Dodie"] />

<cfscript>
for (var i=1; i<=arrayLen(myArray); i++) {
    writeOutput('#i#: #myArray[i]#<br/>');
}
</cfscript>
  • Array loop
for (item in myArray) {
    writeOutput(#item# & '<br/>');
}
  • Sturcture loop
<cfset myStruct = {"name": "Batman",
                   "address": "28 Ocean dr, Miami Beach, FL",
                   "dob": "07/10/1985"} />

<cfscript>
for (key in myStruct) {
    writeOutput('#key#: #myStructure[key]#<br/>');
}
</cfscript>

Flow control inside of cfloop

  • You can use break

break is a reserved word that would terminate the loop when is executed

<cfloop from="1" to="5" index="i">
    <cfif i MOD 2 EQ 0>
        <cfbreak/>
    </cfif>
    <cfoutput>#i#</cfoutput>
</cfloop>
  • Also you can use continue

continue is a reserved word that jumps to the next iteration when is executed

<cfloop from="1" to="5" index="i">
    <cfif i MOD 2 EQ 0>
        <cfcontinue/>
    </cfif>
    <cfoutput>#i#</cfoutput>
</cfloop>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment