PHP - Operator Ternary Operator


The symbol for the ternary operator is ? .

The ternary operator uses three expressions:

( expression1 ) ? expression2 : expression3;

The ternary operator is a compact version of the if...else construct.

The preceding code reads as follows:

If expression1  evaluates to  true , the overall expression equals  expression2 ;
otherwise, the overall expression equals expression3 .



    $widgets = 23;/*from  w ww  .ja v  a 2 s .  c o m*/
    $plenty = "plenty";
    $few = "Less than 10 left.";
    echo ( $widgets  >= 10 ) ? $plenty : $few;


Three variables are created: the $widgets variable, with a value of 23.

Two variables, $plenty and $few , to hold text strings to display to the user.

Finally, the ternary operator is used to display the appropriate message.

The expression $widgets >= 10 is tested; if it's true, the overall expression evaluates to the value of $plenty.

If the test expression happens to be false, the overall expression will take on the value of $few instead.