如果 - 使用条件在字符串中的一个衬垫

时间:2017-08-17 06:49:45

标签: php

有没有办法在字符串中使用条件?

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

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

// Output: hello dear panda

4 个答案:

答案 0 :(得分:4)

您应该将{}替换为()。此外,不需要()周围的$y=='mister'。你应该尝试将它们保持在(可读)最低限度。

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

答案 1 :(得分:4)

对于三元运算符,我们不使用{ }括号,而是必须使用( )

替换您的代码

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

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

答案 2 :(得分:3)

{}替换为(),它将起作用:

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

答案 3 :(得分: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
相关问题