PHP 内联 IF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17016041/
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 12:06:04  来源:igfitidea点击:

PHP Inline IF

phpif-statementsyntax

提问by Graeme

Firstly, PHP is not my forte... although not sure what is!

首先,PHP 不是我的强项...虽然不确定是什么!

I saw an example in the PHP Manual:

我在 PHP 手册中看到了一个例子:

<?php
$var = TRUE;
echo $var==TRUE ? 'TRUE' : 'FALSE'; // get TRUE
echo $var==FALSE ? 'TRUE' : 'FALSE'; // get FALSE
?>

and am trying to integrate something similar as part of a single line output. My line looks like this:

并试图将类似的东西集成为单行输出的一部分。我的线路看起来像这样:

echo "...text..." . $db_field['late']==0 ? ' ' : $db_field['late']  . "...more text...";

Logically what I want to do is: if 'late' = 0 then display nothing else display the content of 'late'.

从逻辑上讲,我想要做的是:如果 'late' = 0 然后不显示任何其他内容显示 'late' 的内容。

Am I just trying to be too clever?

我只是想变得太聪明吗?

Thanks in advance

提前致谢

Graeme

格雷姆

回答by luiges90

Because the precedence of ternary operator ?:is very low. To fix this, use brackets

因为三元运算符的优先级?:很低。要解决此问题,请使用括号

echo "...text..." . ($db_field['late']==0 ? ' ' : $db_field['late']) . "...more text...";

PHP Operator precedence

PHP 运算符优先级

回答by u1813888

echo "...text..." . ( $db_field['late']==0 ? ' ' : $db_field['late'] )  . "...more text...";