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
Jac*_*ers 16
结合mellamokb和Andz你可以这样做:
( $append != 'do' ) ?: $my_string .= ' there';
Run Code Online (Sandbox Code Playgroud)
检查条件然后追加到字符串的另一种方法是:
($append == 'do') and ($my_string .= ' there');
Run Code Online (Sandbox Code Playgroud)
但这实际上只是一个if替代。但是接近“没有其他的三元”。