PHP中拼接操作符内的三元运算符没有else怎么办?

5
我想检查两个变量是否相同,如果相同,就输出一个字符串。在连接操作中是否可以实现这一点?而且要在不创建单独函数的情况下完成?
例如: $var = '这是第一部分,' . ( $foo == $bar ? "可选的中间部分" : '') .'和剩余的字符串。' 注意,我想知道是否有一种方法可以在没有 :'' 的情况下完成以上操作。一种“二进制运算符”的方式。

是的,上面的例子无法运行。 - Andrew Tibbetts
你不能在没有 : 的情况下使用三元运算符。为什么你不想使用它呢? - Marko D
这是多余的 - 只是想缩短一些东西。同时满足我的强迫症。 - Andrew Tibbetts
3个回答

12
不要试图缩短太多。你需要那个: ''才能让事情正常工作。
使用(condition) ? "show when true" : ""根据条件显示可选文本。三元运算符之所以被命名为这样,是因为它由3个部分组成。
$var = 'here is the first part and '. (( $foo == $bar ) ? "the optional middle part" : "") .' and the rest of the string.';

你比之前快了几秒钟。 - Marko D
@MarkoD 但是原帖实际上修改了问题,要求“没有 : ''”。 - Antony
谢谢。在我发布之前,我有点知道这个问题,但希望这可以帮助其他人避免多年找不到明确答案的困扰。 - Andrew Tibbetts
我仍然希望 if only 存在一个“二进制运算符”。 :) - Andrew Tibbetts
如果您喜欢“二进制运算符”:`$var ='这里是第一部分和'; $ foo!== $ bar || $var。=“可选的中间部分”; $ var .='和字符串的其余部分。';' 这并没有真正缩短任何东西。 - Antony
我哥哥有一个创造函数的想法:function concatenable_if ($statement, $value) { if ($statement) return $value; else return ''; } 但是,我还在寻找内置于php中的东西。 - Andrew Tibbetts

1
三元操作符的语法如下:

条件表达式 ? 表达式1 : 表达式2

(any condition)?"return this when condition return true":"return this when condition return false"

所以在您的字符串中应该是这样的。
$var = 'here is the first part and '.( ( $foo == $bar ) ? "the optional middle part":"") .' and the rest of the string.'

这意味着您的条件缺少else过去和运算符优先级。

1
如果问题是“我能不用冒号和空引号吗?”答案是否定的,你必须要有闭合的:'',最好使用括号来明确你的意愿。
$var = 'here is the first part and '. 
        (( $foo == $bar ) ? "the optional middle part":'') .
       ' and the rest of the string.'

我认为这里最大的问题是你试图在行内完成操作。这基本上归结为相同的过程,不使用未关闭的三元运算符:
$var = 'here is the first part and ';
if( $foo == $bar ) $var .= "the optional middle part";
$var .= ' and the rest of the string.';

这是另一种实现相同目标的方法,无需担心条件语句破坏字符串:

$middle = '';
if( $foo == $bar ) $middle = ' the optional middle part and';
$var = sprintf('here is the first part and%s the rest of the string.',$middle);

现在,如果你想要过于聪明地做这件事情,我想你可以尝试这样做:
$arr = array('here is the first part and',
             '', // array filter will remove this part
             'here is the end');
// TRUE evaluates to the key 1. 
$arr[$foo == $bar] = 'here is the middle and';
$var = implode(' ', array_filter($arr));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接