PHP如果速记

med*_*edk 13 php if-statement shorthand-if ternary-operator

我有一个字符串,我想附加一些其他字符串.让我们说:

$my_string = 'Hello';

$my_string .= ' there';
Run Code Online (Sandbox Code Playgroud)

这将返回'你好'.

我想这样做有条件:

$my_string = 'Hello';

$append = 'do';

if ( $append == 'do' ) {

    $my_string .= ' there';

}
Run Code Online (Sandbox Code Playgroud)

现在,我想使用三元运算来做到这一点,但我遇到的所有例子都是if/else wich将是这样的:

$my_string .= ( $append == 'do' ) ? ' there' : '';
Run Code Online (Sandbox Code Playgroud)

那么只用IF而没有其他可能吗?

谢谢.

And*_*ndz 24

不.但是,相反的情况是可能的.以下是PHP文档的引用:

从PHP 5.3开始,可以省略三元运算符的中间部分.表达式expr1?:expr3如果expr1的计算结果为TRUE则返回expr1,否则返回expr3.

http://php.net/manual/en/language.operators.comparison.php


Bue*_*ler 18

不......三元是指你需要条件,真实部分和虚假部分的三个部分


Jac*_*ers 16

结合mellamokb和Andz你可以这样做:

( $append != 'do' ) ?: $my_string .= ' there';
Run Code Online (Sandbox Code Playgroud)

  • +1会说,但无法在ideone上正确测试它:(它确实似乎边缘线不可读,我不推荐它. (3认同)

mar*_*rio 5

检查条件然后追加到字符串的另一种方法是:

 ($append == 'do')  and  ($my_string .= ' there');
Run Code Online (Sandbox Code Playgroud)

但这实际上只是一个if替代。但是接近“没有其他的三元”。

  • 此比较是否有技术名称? (2认同)