74

What is the difference between the two following methods (performance, readability, etc.) and what do you prefer?

echo "Welcome {$name}s!"

vs.

echo "Welcome " . $name . "!";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aley
  • 8,540
  • 7
  • 43
  • 56
  • 4
    Whichever is easier to read.... but as this question is simply polling opinion rather than a question with a definitive or factual answer, then it isn't really appropriate as a SO question – Mark Baker May 28 '13 at 11:09

1 Answers1

62

Whatever works best for you works... But if you want to go for speed use this:

echo 'Welcome ', $name, '!';

The single quotes tell PHP that no interpretation is needed, and the comma tells PHP to just echo the string, no concatenation needed.

Borniet
  • 3,544
  • 4
  • 24
  • 33
  • 40
    The speed difference between single and double quotes is a myth (at least with versions of PHP released this millenium) http://www.phpbench.com/ – Rich Remer Jun 24 '15 at 00:44
  • 12
    My reference to the speed was by using the comma instead of the dot, which is (marginally) faster. And that's also backed by the link you provided. Very interesting link btw!!! – Borniet Jun 24 '15 at 09:03
  • 13
    The performance difference is literally microseconds! On the other hand `echo "Welcome $name!";` is many times more readable. – totymedli Oct 07 '16 at 15:44
  • @Borniet the conclusion does say that using commas with `echo` is faster, but the result above that conclusion prove otherwise. – Kick_the_BUCKET Apr 03 '17 at 07:47
  • I should note string interpolation is a bad habit to be in, in general. If you use it with SQL, of course, your DBA will curse the earth you walk on, and your security consultant will clamor for your retrenchment. Its bad bad news (Always, always use prepared statements, or a battle tested ORM) – Shayne Aug 07 '17 at 07:24
  • 5
    @Shayne It's quite a jump from string interpolation **in SQL** being a bad, bad habit (I wholeheartedly agree!) to string interpolation **in general** being a bad habit. I personally find it more readable (less messy) than concatenation, and use it wherever applicable. Are there any strong arguments against string interpolation in general? – ksadowski Mar 21 '18 at 15:25
  • Not really but i feel it needs to a warning visible to anyone learning about string interpolation, that there are a number of circumstances where the whole thing can get very ugly (with SQL, handling HTML and passing strings to external prcoesses being the big security dangers) – Shayne May 10 '18 at 17:56
  • 2
    @shayne The SQL argument is completely irrelevant to the question, string concatenation is _exactly_ as bad as interpolation, and for _exactly_ the same reasons, in an SQL context. – philomory Oct 18 '18 at 00:37
  • I never said it wasn't. You should never use *any* of those in SQL. – Shayne Nov 19 '18 at 09:24