PHP - concatenate or directly insert variables in string

512,641

Solution 1

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.

Solution 2

Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!

//syntax error!!
//$s = "Hello {trim($world)}!"

//the only option
$s = "Hello " . trim($world) . "!";

Solution 3

Since php4 you can use a string formater:

$num = 5;
$word = 'banana';
$format = 'can you say %d times the word %s';
echo sprintf($format, $num, $word);

Source: sprintf()

Solution 4

I prefer this all the time and found it much easier.

echo "Welcome {$name}!"

Solution 5

Either one is fine. Use the one that has better visibility for you. And speaking of visibility you can also check out printf.

Share:
512,641

Related videos on Youtube

Web_Designer
Author by

Web_Designer

Warning: Stack overflow was a deep pit for me. I wanted to be esteemed by others. But what is highly esteemed by others is detestable in the sight of God. Jesus said, "What would it profit you to gain the whole world and forfeit your soul?" God is patient, but He never fails to fulfill His word. Judgement will come where everyone will be repaid for their deeds. Read the Bible and give up everything to obey Jesus.

Updated on August 12, 2020

Comments

  • Web_Designer
    Web_Designer over 3 years

    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.

    • KJYe.Name
      KJYe.Name about 13 years
      if you were doing the first, i personally prefer single quote echo 'Welcome '.$name.'!';
    • Dejan Marjanović
      Dejan Marjanović about 13 years
    • Khez
      Khez about 13 years
      @kjy112 I said the same thing in my answer, I'm a HUGE fan of single quotes :X
    • KJYe.Name
      KJYe.Name about 13 years
      single quote vs double quote performance, but for something like this you wont' notice much: stackoverflow.com/questions/482202/…
    • Marc B
      Marc B about 13 years
      Personally, I ignore the entire "single quotes are more efficient" and just go for "use whichever quoting style requires the last amount of internal escaping". It is highly unlikely that any code you write will benefit from any MICROSCOPIC gains due to less string parsing v.s. increased string concatenation.
    • Web_Designer
      Web_Designer over 12 years
      @kjy112 would the second method work with single quotes?
    • Damian
      Damian almost 8 years
      Performance loss claim is false. See this article as reference: nikic.github.io/2012/01/09/…
  • Web_Designer
    Web_Designer about 13 years
    Excellent, Thank you! it is very nice to know that I can use my favorite method of inserting it directly into the string, and I am very thankful for now knowing how to separate the variable from the rest of the sting if need be using the {}.
  • Web_Designer
    Web_Designer about 13 years
    Ive got the textarea needed. PSPad rocks.
  • Marc B
    Marc B about 13 years
    You can insert functions semi-indirectly into strings via PHP 5.3 variable functions. $x = function() { ...}; $string = "hello {$x(blah blah blah)}", which works around the "restriction".
  • Marc B
    Marc B about 13 years
    THis applies only to echo, though. Try it for a variable assignment and watch your code blow up.
  • AI52487963
    AI52487963 about 13 years
    @Marc That's cool, I didn't know that! You can also assign the name of an existing function to a variable and do the same thing: $x = 'trim'; $string = "hello {$x('blah blah blah')}";
  • Your Common Sense
    Your Common Sense about 13 years
    that's cool but extremely unreadable, so, one have to avoid it anyway.
  • cHao
    cHao about 13 years
    -1 for premature optimization. The difference in performance is not enough to be a factor unless you're printing millions of times in one script -- and even then, any other processing you do will dwarf the extra couple of seconds you might spend printing one way instead of the other. The major difference between them is readability (which leads me to prefer the second style).
  • Pekka
    Pekka about 13 years
    -1: Using single quotes has no real-life effect on performance whatsoever. The linked page shows differences between the two methods in microseconds, that is 0.000001 seconds. Any database query is going to take hundreds of times that time. This debate is entirely pointless.
  • Your Common Sense
    Your Common Sense about 13 years
    I can try to answer your last question. There are many wild rumors in PHP community and some of them are very strong. It's great struggle to disclose them and takes time. But slowly it's changing. So, the answer you linked to is old one, from the times when people didn't care. While in this one some people answered based on their own experience, not on some article they read.
  • colincameron
    colincameron about 11 years
    Just a note that separating the string literals and variables with commas only works with echo, not anywhere else.
  • Sarath Sadasivan Pillai
    Sarath Sadasivan Pillai almost 9 years
    $s = 'Hello ' . trim($world) .'!'; Try using single quotes when there is nothing to interpolate in string.It will improve performance and can be used as a convention to identify both
  • Fernando Cordeiro
    Fernando Cordeiro over 8 years
    Just pointing out on the performance: time php -r '$string=""; for ($i=0;$i<199999;$i++){ $string = $string.$i; } print("Done!\n");' (Concatenation) actually loses by about 300 milliseconds (for 200.000 items, that's 1 miliseconf per thousand elements on your set...). That's statistical noise, it's impossible to even measure any difference. Considering it's more readable, time php -r '$string=""; for ($i=0;$i<199999;$i++){ $string = "{$string}{$i}"; } print("Done!\n");' (Interpolation) is the undisputed winner...
  • Damian
    Damian almost 8 years
    Performance loss is false +1 @cHao. Here's a article with the metrics proving it. nikic.github.io/2012/01/09/…
  • Máxima Alekz
    Máxima Alekz over 7 years
    If want to use interpolation, you have to use double quotes.
  • evilReiko
    evilReiko about 6 years
    Good point for mentioning \r, \n and \t as other answers didn't include this bit.
  • strix25
    strix25 over 5 years
    is it possible to use functions inside string ? like echo "This is {foo()} nice"; ?
  • Javier Arias
    Javier Arias about 5 years
    By far the safest option. +1 for good practice and general convention matching other languages
  • s3c
    s3c about 4 years
    You should use PDOs instead
  • Alexander Behling
    Alexander Behling about 2 years
    @strix25 No, this is not possible. Moreover, the interpolation method ({}) does not work with constants either. So I don't think that this interpolation is the right way. You should ask yourself why you should not use concatenation. If you can't find a reasonable answer, you should prefer concatenation to interpolation. Although I haven't tested it yet, I don't think there are noticeable performance differences between one method and the other. And if there are any, they are in an imperceptible amount of time (max. any ms), as is the case with the single quote vs. double quote debate.