How do I use the ternary operator ( ? : ) in PHP as a shorthand for “if / else”?

后端 未结 14 1121
我在风中等你
我在风中等你 2020-11-22 08:34

Based on the examples from this page, I have the working and non-working code samples below.

Working code using if statement:

if (!empty         


        
相关标签:
14条回答
  • 2020-11-22 09:28

    The

    (condition) ? /* value to return if condition is true */ 
                : /* value to return if condition is false */ ;
    

    syntax is not a "shorthand if" operator (the ? is called the conditional operator) because you cannot execute code in the same manner as if you did:

    if (condition) {
        /* condition is true, do something like echo */
    }
    else {
        /* condition is false, do something else */
    }
    

    In your example, you are executing the echo statement when the $address is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo the result of the conditional operator:

    echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];
    

    and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

    0 讨论(0)
  • 2020-11-22 09:28

    PHP 7+

    As of PHP 7, this task can be performed simply by using the Null coalescing operator like this :

    echo !empty($address['street2']) ?? 'Empty';

    0 讨论(0)
提交回复
热议问题