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

问题描述 投票:0回答:5

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

expression ? $foo : $bar

情节扭曲:我需要

echo $foo
echo $bar
。有什么疯狂的把戏吗? :)

php if-statement echo shorthand
5个回答
63
投票
<?=(expression) ? $foo : $bar?>

编辑:这里有一本关于这个主题的好书

编辑:更多阅读


11
投票
echo (expression) ? $foo : $bar;

7
投票

如果第一个表达式的计算结果为TRUE

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

echo expression ? $foo : $bar;

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


0
投票

上面的答案很好,我喜欢程序员提出这样的问题来创建清晰、简洁和临床的编码实践。对于任何可能觉得这有用的人:

<?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 ?? '' );

?>

参考文献:


0
投票

另一个自 php 5.3 以来最短的选项:

© www.soinside.com 2019 - 2024. All rights reserved.