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

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

    Quick and short way:

    echo $address['street2'] ? : "No";
    

    Here are some interesting examples, with one or more varied conditions.

    $color = "blue";
    
    // Condition #1 Show color without specifying variable 
    echo $color ? : "Undefined";
    echo "
    "; // Condition #2 echo $color ? $color : "Undefined"; echo "
    "; // Condition #3 echo ($color) ? $color : "Undefined"; echo "
    "; // Condition #4 echo ($color == "blue") ? $color : "Undefined"; echo "
    "; // Condition #5 echo ($color == "" ? $color : ($color == "blue" ? $color : "Undefined")); echo "
    "; // Condition #6 echo ($color == "blue" ? $color : ($color == "" ? $color : ($color == "" ? $color : "Undefined"))); echo "
    "; // Condition #7 echo ($color != "") ? ($color != "" ? ($color == "blue" ? $color : "Undefined") : "Undefined") : "Undefined"; echo "
    ";

提交回复
热议问题