如果速记单行,什么是最好的、首选的写作方式,例如:
expression ? $foo : $bar
情节扭曲:我需要
echo $foo
或echo $bar
。有什么疯狂的把戏吗? :)
echo (expression) ? $foo : $bar;
如果第一个表达式的计算结果为TRUE
,
三元运算符计算第二个表达式的值,如果第一个表达式的计算结果为
FALSE
,则计算第三个表达式的值。要 echo
一个值或另一个,只需将三元表达式传递给 echo
语句。
echo expression ? $foo : $bar;
阅读 PHP 手册中有关三元运算符的更多详细信息:http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
上面的答案很好,我喜欢程序员提出这样的问题来创建清晰、简洁和临床的编码实践。对于任何可能觉得这有用的人:
<?php
// grabbing the value from a function, this is just an example
$value = function_to_return_value(); // returns value || FALSE
// the following structures an output if $value is not FALSE
echo ( !$value ? '' : '<div>'. $value .'</div>' );
// the following will echo $value if exists, and nothing if not
echo $value ?: '';
// OR (same thing as)
echo ( $value ?: '' );
// or null coalesce operator
echo $value ?? '';
// OR (same thing as)
echo ( $value ?? '' );
?>
参考文献:
另一个自 php 5.3 以来最短的选项: