1

I have a loop which I need to add in the index to a function call. How can I do this?

Here is what I tried but it fails

<cfloop index="i" from="1" to="#arrayLen(test)#">
    #session_ID & i &.getSessionCount()#
</cfloop>

The index of the loop should output so that each iteration of the loop the line would look like this:

#session_ID1.getSessionCount()#
#session_ID2.getSessionCount()#
#session_ID3.getSessionCount()#
#session_ID4.getSessionCount()#

and so on.

4
  • Can you expand on using evaluate? Commented Jul 6, 2015 at 21:53
  • @Kevin B this seems to be giving me the correct output now: #evaluate("session_ID" & i).getSessionCount()# thank you i will go with this for now. Commented Jul 6, 2015 at 22:05
  • 1
    in the past i've used evaluate for things like this, but i read a post on here a while back about how you should avoid using it! if you check this page 'Avoiding the Evaluate function' help.adobe.com/en_US/ColdFusion/9.0/Developing/… it gives you alternatives Commented Jul 6, 2015 at 22:08
  • 4
    Using evaluate() is unnecessary here, and is generally considered poor practice in general. Commented Jul 6, 2015 at 22:10

1 Answer 1

9

If one needs to create a variable name dynamically, then use associative array notation rather than dot notation, and reference the variable via the scope that it's in. EG:

<cfloop index="i" from="1" to="#arrayLen(test)#">
    <cfset result = variables["session_ID" & i].getSessionCount()>
</cfloop>
Sign up to request clarification or add additional context in comments.

1 Comment

After so more reading and looking at Adam's example using the associative array notation i have gone with this. Thanks guys, i'm putting this down to learning something else new today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.