Xbasic

IF Function

Syntax

Value as A = IF(L condition,A result_true,A result_false)

Arguments

condition

Logical. An expression that evaluates to .T. (TRUE) or .F. (FALSE).

result_true

Any type. A value.

result_false

Any type. A value of the same type as True_Value (i.e. character, date, logical, memo, or numeric).

Description

Tests an expression and returns one of two expressions.

Discussion

IF() evaluates the Logical_Expression and returns the True_Value if the Logical_Expression evaluates to . T. (TRUE) ; otherwise it returns the False_Value. For example: IF(.T., "ABCDEF", "XYZ") ?ABCDEF". Note : When writing an Xbasic script, you cannot use the IF() function because it will be confused with the if ..then statement. Instead, you must use the IIF() function.

if(STATE = "MA", .05, 0) -> .05, if STATE contains "MA"
if(PAID, "Paid", "Outstanding") ->  "Paid", if PAID (a logical field) is TRUE

Suppose that your company offers a discount based on the total amount of goods purchased. Customers buying over $1,000 worth of merchandise receive a 10% discount. The amount of the order before the discount is kept in a field called SUBTOTAL. You can make DISCOUNT a calculated field, using the following expression:

if(SUBTOTAL > 1000, .1, 0)

If the value of SUBTOTAL is greater than 1000, then the value of DISCOUNT is .1 (10%). If the value of SUBTOTAL is not greater than 1000, then the value of DISCOUNT is 0.

Nested If Statements 

You can nest IF() statements to create more complex tests. For example, assume that you use codes to save data entry time when entering college students into a table. The field CLASS contains 1 for "Freshman", 2 for "Sophomore", 3 for "Junior", and 4 for "Senior". To print a report that contains the year of school a student is in, rather than the code, define and place a calculated field called GRADE, which uses the following expression:

if(class=4, "Senior", if(class=3, "Junior", if(class=2, "Sophomore", "Freshman")))

If the CLASS is 4, then the TRUE action is taken and the expression returns "Senior." If the first test is FALSE, then the false action is taken. The false action in this case is another IF() statement. The second IF() tests CLASS to see if it is 3. If TRUE, then the expression returns "Junior." However, if the second test also fails, then the third IF() is evaluated. The third IF() tests to see if class=2. If so, the expression returns "Sophomore." If the third test fails the false action is taken. At this point, you have already tested for the other possibilities, so no further test is necessary. The student must be a "freshman."

See Also