PHP – concatenate or directly insert variables in string

Between those two syntaxes, you should really choose the one you prefer 🙂

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

The result will be the same; and even if there are performance implications, those won’t matter 1.

As a sidenote, so my answer is a bit more complete: the day you’ll want to do something like this:

echo "Welcome $names!";

PHP will interpret your code as if you were trying to use the $names variable — which doesn’t exist.
– note that it will only work if you use “” not ” for your string.

That day, you’ll need to use {}:

echo "Welcome {$name}s!"

No need to fallback to concatenations.

Also note that your first syntax:

echo "Welcome ".$name."!";

Could probably be optimized, avoiding concatenations, using:

echo "Welcome ", $name, "!";

(But, as I said earlier, this doesn’t matter much…)

1 – Unless you are doing hundreds of thousands of concatenations vs interpolations — and it’s probably not quite the case.

Leave a Comment