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

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

    Conditional Welcome Message

    echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';
    

    Nested PHP Shorthand

    echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );
    

提交回复
热议问题