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

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

    Ternary Operator is basically shorthand for if/else statement. We can use to reduce few lines of code and increases readability.

    Your code looks cleaner to me. But we can add more cleaner way as follows-

    $test = (empty($address['street2'])) ? 'Yes
    ' : 'No
    ';

    Another way-

    $test = ((empty($address['street2'])) ? 'Yes
    ' : 'No
    ');

    Note- I have added bracket to whole expression to make it cleaner. I used to do this usually to increase readability. With PHP7 we can use Null Coalescing Operator / php 7 ?? operator for better approach. But your requirement it does not fit.

提交回复
热议问题