Expression evaluation in interpolated strings in PHP

316 Views Asked by At

In JavaScript, you can do this:

console.log(`Hello ${3 + 4} World.`)

The out put will be Hello 7 World. I can do the same in C# with Console.WriteLine($"Hello {3 + 4} World").

In PHP I tried:

echo "Hello {3 + 4} World."

However the output of this is Hello {3 + 4} World.

How do I interpolate expressions in strings in PHP?

2

There are 2 best solutions below

1
John On

You can use this : echo "Hello ".(3+4)." World.";

0
nikodem0808 On

It is not possible to evaluate arbitrary expressions during string interpolation in PHP. You have to either define a variable or use the syntax from John's answer.