Is there a way to use conditions in string?
$x = 'hello';
$y = 'mister'; // is nullable
$z = 'panda';
$msg = $x . ' ' . {($y == 'mister') ? 'dear ' : ' ' } . $z
// Output: hello dear panda
Is there a way to use conditions in string?
$x = 'hello';
$y = 'mister'; // is nullable
$z = 'panda';
$msg = $x . ' ' . {($y == 'mister') ? 'dear ' : ' ' } . $z
// Output: hello dear panda
You should replace the {}
with ()
. Also, the ()
around the $y=='mister'
are not needed. You should try to keep those to a (readable) minimum.
$msg = $x . ' ' . ($y == 'mister' ? 'dear ' : ' ' ) . $z;
for Ternary operator we are not using { }
brackets,instead you have to use ( )
.
Replace your code
$msg = $x . ' ' . {($y == 'mister') ? 'dear ' : ' ' } . $z
with
$msg = $x . ' ' . (($y == 'mister') ? 'dear ' : ' ' ) . $z
Replace {}
with ()
and it will work:
$x = 'hello';
$y = 'mister'; // is nullable
$z = 'panda';
$msg = $x . ' ' . (($y == 'mister') ? 'dear ' : ' ' ) . $z;
echo $msg;
If I am understanding your question well, you do not intend to find out whether you can use a condition inside a string, but you want to assign a value to a string. The value to be assigned depends on a condition, which could be written like
$x = 'hello';
$y = 'mister'; // is nullable
$z = 'panda';
$msg = $x . ' ';
if ($y == 'mister') {
$msg .= $x . 'dear ';
}
$msg .= $z;
// Output: hello dear panda
However, this is a bit long and you intended to use the ? operator. The mistake was that you used the curly brackets {}. This is the fix:
$x = 'hello';
$y = 'mister'; // is nullable
$z = 'panda';
$msg = $x . ' ' . (($y == 'mister') ? 'dear ' : ' ' ) . $z;
// Output: hello dear panda