我想检查两个变量是否相同,如果是,回显字符串。这在串联中可能吗?在不创建一个单独的函数的情况下?
。
$var = 'here is the first part and '. ( $foo == $bar ) ? "the optional middle part" .' and the rest of the string.'
编辑
注意,我正在寻找是否有一种方法来做到没有 : ''
。
不要试图将内容缩短太多。你需要的: ''
为了事情的工作。
使用(condition) ? "show when true" : ""
根据条件显示可选文本。三元操作符这样命名是因为它由3部分组成。
$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 '.
(( $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));
三元运算符语法如下
(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.'
,这意味着你的条件是缺失的,否则过去和操作符优先