2017-08-17 60 views
1

是否有字符串使用条件的方法吗?一个衬垫,如果 - 使用条件字符串

$x = 'hello'; 
$y = 'mister'; // is nullable 
$z = 'panda'; 

$msg = $x . ' ' . {($y == 'mister') ? 'dear ' : ' ' } . $z 

// Output: hello dear panda 
+0

问题是什么? – Andreas

+0

你做对了,你所要做的就是掉花括号用括号。 – MinistryofChaps

+2

用'()替换'{}'。 –

回答

3

更换{}(),它会工作:

$x = 'hello'; 
$y = 'mister'; // is nullable 
$z = 'panda'; 
$msg = $x . ' ' . (($y == 'mister') ? 'dear ' : ' ') . $z; 
echo $msg; 
+0

奇怪,你的回答是正确的,那么为什么你投下了 –

+0

@JigarShah我们永远不会知道) –

4

你应该()更换{}。此外,$y=='mister'围绕()是不需要的。你应该尽量保持这些(可读)最小。

$msg = $x . ' ' . ($y == 'mister' ? 'dear ' : ' ') . $z; 
4
为三元操作

我们没有使用{ }括号,而不是必须使用()

替换代码

$msg = $x . ' ' . {($y == 'mister') ? 'dear ' : ' ' } . $z

$msg = $x . ' ' . (($y == 'mister') ? 'dear ' : ' ') . $z

0

如果我理解你的问题好了,你不打算找出你是否可以使用字符串中的条件,但是你想为一个字符串赋值。要分配的值取决于一个条件,这可能是这样写

$x = 'hello'; 
$y = 'mister'; // is nullable 
$z = 'panda'; 

$msg = $x . ' '; 
if ($y == 'mister') { 
    $msg .= $x . 'dear '; 
} 
$msg .= $z; 

// Output: hello dear panda 

然而,这是一个有点长,你打算使用?运营商。错误在于你使用了大括号{}。这是修复:

$x = 'hello'; 
$y = 'mister'; // is nullable 
$z = 'panda'; 

$msg = $x . ' ' . (($y == 'mister') ? 'dear ' : ' ') . $z; 

// Output: hello dear panda