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.

Categories

Data Structures

Comments

comments powered by Disqus