Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

How do you dynamically set a variable and its value?

You need to set a value to a variable but the name of the variable is also to be set dynamically, for instance the variable name and variable value maybe stored in the database. This can be done in ColdFusion multiple ways. The first, and probably preferred way, is to use structure notation:

<cfset varname = "name">
<cfset value = "Jacob">
<cfset variables[varname] = value>

This code simply treats the local variables scope as a structure. The next way lets ColdFusion evaluate the left hand side of an expression to determine the variable name:

<cfset varname = "name">
<cfset value = "Jacob">
<cfset "#varname#" = value>

Lastly, you can use the setVariable() function to create a variable:

<cfset varname = "name">
<cfset value = "Jacob">
<cfset setVariable(varname, value)>


This question was written by Martin Thorpe.
It was last updated on March 2, 2006 at 6:10:34 AM EST.

CFML Referenced

SetVariable()

Categories

Data Structures

Comments

Comment made by Dave Levin on April 26, 2006 at 8:17 PM
Great explanation. Can you use dynamic variable names with using CFPARAM though? From what I've read, you can use dynamic names like var_#i# but not #i# in a CFPARAM tag.

<A href="http://www.angrysam.com">David Levin</a>


Comment made by Raymond Camden on April 27, 2006 at 7:13 AM
Yes, but normally it isn't used quite like that. The typical usecase of cfparam is, "I may have X defined, if not, default it to this." I'm splitting hairs, but you get the difference I think.


Comment made by Peter Bell on May 31, 2006 at 8:42 PM
You can use dynamic values in cfparam (unless I'm missing the point here). Imagine use case where you have a list of fields that may or may not exist in the form and want to write a generic form processor that includes paraming the form values.

<cfset MyList = "a,b,c"> <cfloop list="#MyList#" index="VarName"> <cfparam name="form.#VarName#" default="1"> </cfloop> <cfoutput> a = #form.a#<br /> b = #form.b#<br /> c = #form.c#<br /> </cfoutput>

The above code runs fine and also works if you just set #VarName# - not form.#VarName#. Is that what you were looking for?