PHP variable interpolation vs concatenation

92,845

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.

Share:
92,845
Aley
Author by

Aley

Updated on July 05, 2022

Comments

  • Aley
    Aley almost 2 years

    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 . "!";
    
  • Rich Remer
    Rich Remer almost 9 years
    The speed difference between single and double quotes is a myth (at least with versions of PHP released this millenium) phpbench.com
  • Borniet
    Borniet almost 9 years
    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!!!
  • totymedli
    totymedli over 7 years
    The performance difference is literally microseconds! On the other hand echo "Welcome $name!"; is many times more readable.
  • Kick_the_BUCKET
    Kick_the_BUCKET about 7 years
    @Borniet the conclusion does say that using commas with echo is faster, but the result above that conclusion prove otherwise.
  • Shayne
    Shayne over 6 years
    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)
  • ksadowski
    ksadowski about 6 years
    @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?
  • Shayne
    Shayne almost 6 years
    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)
  • philomory
    philomory over 5 years
    @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.
  • Shayne
    Shayne over 5 years
    I never said it wasn't. You should never use any of those in SQL.