The function evaluates condition as a Boolean. If the result is TRUE, it returns the value of Evaluate(string_expression1)
; otherwise, it returns the value of Evaluate(string_expression2)
.
Before using IIf
, read the Usage section and Note. IIf
is primarily intended for the conditional processing of dynamic expressions.
For general conditional processing, see cfif cfelseif cfelse. For error handling, see cftry cfcatch.
IIf(condition, string_expression1, string_expression2)
DE (Delay Evaluation),
Evaluate
The IIf
function is a shortcut for the following construct:
<cfif condition>
<cfset result = Evaluate(string_expression1)> <cfelse> <cfset result = Evaluate(string_expression2)> </cfif>
returning result. The expressions string_expression1 and string_expression2 must be string expressions, so that they are not evaluated immediately as the arguments of IIf
. For example:
IIf(y is 0, DE("Error"), x/y)
generates an error if y = 0
, because the third argument is the value of x/0 (invalid expression).
Recall that ColdFusion evaluates string_expression1 and string_expression2. To return the string itself, use the DE (Delay Evaluation) (delay evaluation) function.
Note If you use pound signs (#) in string_expression1 or string_expression2, ColdFusion evaluates the part of the expression in pound signs first. By misusing pound signs, you can skew the results of the |
For example, LocalVar
is undefined; however, the following logic functions as you would expect if you do not use pound signs around LocalVal
:
<cfoutput>
#IIf(IsDefined("LocalVar"), "LocalVar", DE("The variable is not defined."))# </cfoutput>
The variable is not defined.
Whereas, the pound signs around LocalVar
in the following code cause it to fail with the error message 'Error Resolving Parameter', because ColdFusion never evaluates the original condition IsDefined("LocalVar")
.
<cfoutput>
#IIf(IsDefined("LocalVar"), DE("#LocalVar#"), DE("The variable is not defined."))# </cfoutput>
Error resolving parameter LOCALVAR
The DE
function has no impact on the evaluation of LocalVal
, since the pound signs cause it to be evaluated immediately.
<!--- This example shows IIf ---> <html> <head> <title>IIf Example</title> </head> <body bgcolor = silver> <H3>IIf Function</H3> <P>IIf evaluates a condition, and does an Evaluate on string expression 1 or string expression 2 depending on the Boolean outcome <I>(TRUE: run expression 1; FALSE: run expression 2)</I>. </P> <P>The result of the expression IIf( Hour(Now()) GT 12, DE("It is afternoon or evening"), DE("It is morning")) is:<BR> <cfoutput> #IIf( Hour(Now()) GT 12, DE("It is afternoon or evening"), DE("It is morning"))# </cfoutput> </P> </body> </html>