Home PHP How to use Ternary Operator in PHP

How to use Ternary Operator in PHP

In programming, evaluating conditional statements is essential. The ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures. It takes three operands – a condition, a result for true, and a result for false. A ternary ? : is simply shorthand for if and else.

Now, let’s move to the example. The syntax of a ternary operator may be confusing at first sight, but it is much easier when you understand it. The basic syntax of Ternary operator is:

(expr1) ? (expr2) : (expr3)

Here, The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Real world Example:

$var = 10;
$result = ($var > 5 ? true : false); 

In this example, 10 is assigned to $var variable. In second line, it check the condition: is $variable is greater than 5 or not. It, it is true, it returns true, else returns false. In this case, it return true which is assigned to $result.

Another example from php.net

// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];


Ternary shorthand

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
expr1 ?: expr2
Here, the expression evaluates to the value of expr1 if expr1 is true and expr2 otherwise:
Advantages of Ternary Operator:
• Easy to read
• Easy to understand
• Easy to modify
• Minimize code

Abuse of Ternary Operator

Ternary operator are very flexible if used properly but can be very confusing and increase the complexity if used improperly. Try not to use Ternary Operator in complex group of lines which will ultimately increase the complexity of code rather than minimizing the code.

Please note that the ternary operator is an expression, and that it doesn’t evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.



Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version