PHP Ternary Operator

In simple words, PHP Ternary Operator is a shortened method of writing an if-else statement.

In mathematics, Ternary is n -ary with n=3 which means three Operations. Same in programming languages like PHP, Ternary operator takes following three operands to perform its action:

  • First argument is a Condition
  • Second is a result in case condition is true
  • Third is a result in case condition is false

Syntax
$result = $condition ? 'true result' : 'false result';


Why we use Ternary Operator:

Let’s suppose, we need to check if a number is less than 10 or not. One way is to use ‘Decision Making Statements’ and the second one is by using ‘Ternary Operator’. Ternary Operator can perform the same operation in a single line as compared to Conditional statement which uses multiple lines. Therefore, it reduces the length of your code.

Note: If you are not proficient in PHP code, use Decision Making Statements instead. Because in Ternary Operator, you are more likely to make mistakes while Decision Making Statements are easy to understand.


Example using Simple If else:

<?php
$number=9;
    if ($number < 10) {
        $number_check = 'less than 10';
    } else {
        $number_check = 'not less than 10';
    }
 
    echo $number_check;
?>
Tutorials Class - Output Window

less than 10


Example using Ternary Operator:

Now, you can see the same program by Ternary Operator.

<?php
    $number=12;
    $number_check = ($number < 10) ? 'less than 10' : 'not less than 10';
    echo $number_check;
?>
Tutorials Class - Output Window

not less than 10


Example using Multiple Ternary Operator:

Now, you can see the same program by PHP Multiple Ternary Operator to check equal value as well.

<?php
    $number=10;
    $number_check = ($number <10) ? "less than 10" : (($number == 10)  ? "equal to 10" : "not less than 10");
    echo $number_check;
?>
Tutorials Class - Output Window

equal to 10

Now you can see, by using ternary Operator we have compacted the multiple lines of code into one.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.