PHP 如果速记并在一行中回显 - 可能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20233207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:59:30  来源:igfitidea点击:

PHP if shorthand and echo in one line - possible?

phpif-statementechoshorthand

提问by Wordpressor

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

如果速记单行,最好的首选书写方式是什么,例如:

expression ? $foo : $bar

Plot twist: I need to echo $fooor echo $bar. Any crazy tricks? :)

情节扭曲:我需要echo $fooecho $bar。有什么疯狂的技巧吗?:)

回答by Dave

回答by A.M.N.Bandara

echo expression ? $foo : $bar;

回声表达 ? $foo : $bar;

回答by A.M.N.Bandara

The ternary operatorevaluates 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 echoone value or the other, just pass the ternary expression to the echostatement.

三元运算符的计算结果为第二个表达式,如果第一个计算结果为的值TRUE,并计算结果为第三个表达式如果第一计算结果为FALSE。对于echo一个或另一个值,只需将三元表达式传递给echo语句。

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

在 PHP 手册中阅读有关三元运算符的更多详细信息:http: //php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary