1

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
senty
  • 12,385
  • 28
  • 130
  • 260

4 Answers4

4

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;
Martijn
  • 15,791
  • 4
  • 36
  • 68
Aakash Martand
  • 926
  • 1
  • 8
  • 21
4

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

Moby M
  • 910
  • 2
  • 7
  • 26
3

Replace {} with () and it will work:

$x = 'hello';
$y = 'mister'; // is nullable
$z = 'panda';
$msg = $x . ' ' . (($y == 'mister') ? 'dear ' : ' ' ) . $z;
echo $msg;
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

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
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175