PHP – concatenate or directly insert variables in string

I am wondering, What is the proper way for inserting PHP variables into a string?

This way:

echo "Welcome ".$name."!"

Or this way:

echo "Welcome $name!"

Both of these methods work in my PHP v5.3.5. The latter is shorter and simpler but I’m not sure if the first is better formatting or accepted as more proper.


Answer

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 Reply

Your email address will not be published. Required fields are marked *