Simon Baynes: Web Development

Using Array Notation in ColdFusion

Referencing dynamic variable names can be tricky, unless you are aware of a few basic ColdFusion concepts.

I see things like this:-

<cfloop collection="#form#" item="iFormKey">  
    <cfset temp = evaluate(form.#iFormKey#)>
    #temp#
</cfloop>

and it drives me insane. It is so unnecessary not to mention messy.

Here it is again but using array notation.

<cfloop collection="#form#"; item="iFormKey">
    #form[iFormKey]#
</cfloop>

Now this is not only optimal it is also clear. If you find yourself using the evaluate() function you are either going about it in the wrong way or you are trying to cheat ColdFusion into doing something that it doesn't want to do.

Also bear in mind that barring a few exceptions all ColdFusion variables are in a struct.

<cfscript>
    myVar1 = 1;
    myVar2 = 2;
    myVar3 = 3;
    myVar4 = 4;
    myVar5 = 5;

    for (i = 1; i LTE 5; i = i + 1) {
        // now we use the fact that by default any non-scoped variables are put in the variables scope to our advantage
        writeOutput(variables["myVar" & i] & "<br />");
    }

</cfscript>

So as you can see array notation is very powerful and clean.

By Simon Baynes