If

The if function can be used to output a specific output or other transformation, based on the evaluation of a boolean value.

Syntax

any if(any $condition, any $trueValue, any $falseValue)

Parameters

$condition: The boolean value that should be evaluated upon. A boolean value always returns either true or false, based on the comparison operator. It evaluates as a truthy whereas a non-empty string will evaluate as true. The condition can be set by the operators below:

! NOTThe not operator is used to check if a variable is not true. In other words, it checks boolean values of a statement. This could be e.g., to check if a variable exists or not.
!=Not EqualThe not equal is usually used to check if a value is not equal (a != b)
&&ANDIf you want two or more variables to both be true, you use the && operator
||ORUse this operator if you want just one of more values to be true
<Less thanCheck if one value is less than some other value
>Greater thanCheck if one value is greater than another
==EqualsCheck if two values are equal to each other
<=Less than or EqualCheck if a value is less than or equal to each other
>=Greater than or EqualCheck if a value is greater than or equal to each other
?Filter ExpressionThis is used to filter an array

$trueValue: The value that should be returned if $condition is true. Can also be a transformation.

$falseValue: The value that should be returned if $condition is false. Can also be a transformation.

Example

{
    "a": "Test",
    "b": true,
    "c": "",
    "d": null,
    "e": false
}
{
    alpha: if(a, 'Evaluates true', 'Evaluates false'),
    beta: if(b, 'Evaluates true', 'Evaluates false'),
    charlie: if(c, 'Evaluates true', 'Evaluates false'),
    delta: if(d, 'Evaluates true', 'Evaluates false'),
    echo: if(e, 'Evaluates true', 'Evaluates false'),
    foxtrot: if(a == 'Test', 'Evaluates true', 'Evaluates false')
}
{
    "alpha": "Evaluates true",
    "beta": "Evaluates true",
    "charlie": "Evaluates false",
    "delta": "Evaluates false",
    "echo": "Evaluates false",
    "foxtrot": "Evaluates true"
}

In this example, the values evaluate either true or false. Specifically, it returns either the string “Evaluates true” or “Evaluates false.” Note how the final transformation, “foxtrot,” makes a comparison, and asks whether or not “a” is the same as the value “Test.” Also, the empty string and null value make the if function evaluates as false, for example, “charlie” and “delta.”

Notes

Error handling

The if function is useful for error handling a transformation. For example, if an input is expected to be an array, and some array-specific operations is supposed to be executed on the input, it would be beneficial to encapsulate the operation with an if like if(arr1 == to_array(arr1), to_array(arr1), split_array(arr1, 2), ''), where the false output would give an empty string, instead of an error.