Skip to Content

Create Variables & Set Values with CFSet in CFML

In this tutorial, you'll learn how to create variables, arrays, structures, and more using the cfset tag in CFML.

Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

The Attributes

The two attributes for the cfset tag are:

  • variable_name string - The name of the variable; required.
  • var - An optional keyword without a value assignment that identifies the variable as being local to a function. This variable will only exist at the time of function invocation.
<cfset var variable_name = value>

Code Examples

Create Numeric & String Variables

<cfset id = 1>
<cfset my_var = "This is a string">

Create Variables with Dynamic Names

<cfset my_var = "my_value">
<cfset "#my_var#" = 7>

Create Arrays

<cfset my_array = ArrayNew(1)>
<cfset my_array = ["A", "B", "C", 1, 2, 3]>

Create Structures

<cfset my_struct = StructNew()>
<cfset StructInsert(my_struct, "id", 1)>
<cfset StructInsert(my_struct, "name", "Orangeable")>

<cfset my_struct = {
"id" = 1,
"name" = "Orangeable"
}>

Call Functions

With function calls, the var keyword must be used for local variable assignments and defined at the top of the function. Here's an example:

<cffunction name="myFunc" returnType="string" output="false">
<cfargument name="message" type="string" required="false">
<cfset var my_var = "Foo">

<cfreturn my_var & "bar" & " - " & arguments.message>
</cffunction>

<cfset myFunc(message = "Hello There!")>

The output of the resulting function call with be:

Foobar - Hello There!

Conclusion

In this tutorial, you learned about variable assignments with the cfset tag in CFML.

Posted by: Josh Rowe
Created: July 20, 2023

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.