PHP if shorthand and echo in one line - possible?

前端 未结 3 537
抹茶落季
抹茶落季 2021-01-07 17:44

What\'s the best, preferred way of writing if shorthand one-liner such as:

expression ? $foo : $bar

Plot twist: I need to echo $foo

相关标签:
3条回答
  • 2021-01-07 18:09

    The ternary operator evaluates to the value of the second expression if the first one evaluates to TRUE, and evaluates to the third expression if the first evaluates to FALSE. To echo one value or the other, just pass the ternary expression to the echo statement.

    echo expression ? $foo : $bar;
    

    Read more about the ternary operator in the PHP manual for more details: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

    0 讨论(0)
  • 2021-01-07 18:26

    echo expression ? $foo : $bar;

    0 讨论(0)
  • 2021-01-07 18:35
    <?=(expression) ? $foo : $bar?>
    

    edit: here's a good read for you on the topic

    edit: more to read

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