If

What is it?

The If function requires three arguments, the first of which is an expression known as a Predicate, and the remaining arguments are potential end values for the If function. Depending on whether the expression evaluates to True or False, the value of the If function will be either the second argument (or Consequent, if True) or the third argument (or Alternative, if False).

What is the Syntax?

The basic syntax of the If statement is as follows:

If ( Predicate, Consequent, Alternative );

For example, consider the following function:

TimeOfDay := If( Time > 12 , "Afternoon", "Morning" );

The predicate here is “Time > 12”, meaning the statement will be True if the value of Time is greater than 12:

  • If the predicate evaluates to True, the value of the If statement will be the Consequent, which in this case is “afternoon”.
  • If the predicate evaluates to False, the value of the If statement will be the Alternative, which in this case is “morning”.

The function can therefore be interpreted as “If the current time is after 12, the time of day is afternoon, otherwise it is morning”.

Although If statements are limited to two branches, you can use nesting to add additional branches. Function Nesting is discussed later in this guide.

Why might I want to use this?

The If statement is one of the simplest functions in the Expression Engine, but is nonetheless integral to constructing conditional logic. Any situation where you want to create multiple possible outcomes in your expression, you can use an If statement. Doing this in programming is known as Branching your code.

For example, say you want to assign a group of football players into two teams based on a number they pick out of a hat. The numbers range from 1-22, with all the people with numbers from 1 to 11 being assigned to the blue team, and numbers 12 and up being assigned to the red team.

AssignedTeam := If( PickedNumber <= 11, "Blue", "Red" );

As you can see, the predicate here is “PickedNumber <= 11”, meaning that if the value of PickedNumber is less than or equal to 11, the predicate equates to True and the value of AssignedTeam will be the consequent (“Blue”). Otherwise, the value of AssignedTeam is that of the alternative (“Red”).

 

<< Previous: Concatenate (Concat) | Next: Nesting Functions >>