What is the ternary operator?


Nitin Venkatesh's Gravatar

Nitin Venkatesh
published Feb. 5, 2013, 6:41 a.m.


The ternary operator is used to write a very short version of an if-else block (in one line) and is used in a number of programming languages. The format of using a ternary operator is

(condtion) ? truth statement : false statement

Let’s see a simple example in PHP to check if the number stored in the variable is 1 or not,

 echo ($var == 1) ? 'Number stored is 1' : 'Number stored is not one' ;

The same thing in a full if-else block would be as follows:

if ($var == 1){
    echo "Number stored is 1";
}
else{
    echo "Number stored is not one";
}

We can also use nested ternary operators just as we would use nested if-loops. Here’s an example in PHP to check if the number is either 0 or 1, both using ternary operators and using full if-else blocks:

/* Ternary operator */
echo ($var != 0) ? ($var != 1) ? 'not zero & not one' : 'one' : 'zero' ;

/* Full if-else blocks */
if($var != 0){
    if($var != 1){
        echo 'not zero & not one';
    }
    else{
        echo 'one';
    }
}
else{
    echo 'zero';
}