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

后端 未结 14 1398
我在风中等你
我在风中等你 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:22

    There's also a shorthand ternary operator and it looks like this:

    (expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.

    Example:

    $a = 'Apples';
    echo ($a ?: 'Oranges') . ' are great!';
    

    will return

    Apples are great!
    

    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.

    From the PHP Manual

提交回复
热议问题