PHP - concatenate or directly insert variables in string
Asked Answered
T

16

304

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.

Thoracotomy answered 9/4, 2011 at 15:39 Comment(7)
if you were doing the first, i personally prefer single quote echo 'Welcome '.$name.'!';Conjure
php.net/manual/en/…Cringe
single quote vs double quote performance, but for something like this you wont' notice much: #482702Conjure
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.Ephemeral
@kjy112 would the second method work with single quotes?Thoracotomy
Performance loss claim is false. See this article as reference: nikic.github.io/2012/01/09/…Hypochondria
This is funny; how does one define "notice much?" Even back in 2011 the difference would be in the noise on the sub-millisecond level. No human could possibly have noticed at all, right? This notion of speed difference is probably even more dubious than the (now proven false) claim that professional cellists can tell a Stradivarius from a clone.Crifasi
T
455

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.

Thirzi answered 9/4, 2011 at 15:40 Comment(5)
Just a note that separating the string literals and variables with commas only works with echo, not anywhere else.Martie
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...Matronize
If want to use interpolation, you have to use double quotes.Rocket
is it possible to use functions inside string ? like echo "This is {foo()} nice"; ?Letta
@Letta 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.Caddoan
H
25

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) . "!";
Hassock answered 9/4, 2011 at 15:52 Comment(4)
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".Ephemeral
@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')}";Hassock
that's cool but extremely unreadable, so, one have to avoid it anyway.Purslane
$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 bothAland
D
16

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()

Damask answered 11/3, 2016 at 19:18 Comment(1)
By far the safest option. +1 for good practice and general convention matching other languagesOrangy
J
14

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

echo "Welcome {$name}!"
Josi answered 12/8, 2020 at 3:14 Comment(1)
This also works fine with nested arrays like $matches[0][1]Phane
I
6

From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn't matter here):

  • Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimensional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

  • You frequently need to add crutches such as {} and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.

  • As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.

  • AFAIK, you cannot embed constants.

In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)

Imine answered 23/8, 2011 at 12:8 Comment(0)
T
5

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

Thermonuclear answered 9/4, 2011 at 15:43 Comment(0)
S
5

I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.

Sarinasarine answered 13/4, 2013 at 23:20 Comment(0)
S
5

I use a dot(.) to concate string and variable. like this-

echo "Hello ".$var;

Sometimes, I use curly braces to concate string and variable that looks like this-

echo "Hello {$var}";
Scag answered 12/8, 2020 at 3:41 Comment(0)
W
3

Go with the first and use single quotes!

  1. It's easier to read, meaning other programmers will know what's happening
  2. It works slightly faster, the way opcodes are created when PHP dissects your source code, it's basically gonna do that anyway, so give it a helping hand!
  3. If you also use single quotes instead of double quotes you'll boost your performance even more.

The only situations when you should use double quotes, is when you need \r, \n, \t! The overhead is just not worth it to use it in any other case.

You should also check PHP variable concatenation, phpbench.com for some benchmarks on different methods of doing things.

Wondrous answered 9/4, 2011 at 15:46 Comment(2)
-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.Krause
Good point for mentioning \r, \n and \t as other answers didn't include this bit.Valletta
P
3

Do not concatenate. It's not needed, us commas as echo can take multiple parameters

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

Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.

Pristine answered 9/4, 2011 at 16:0 Comment(1)
THis applies only to echo, though. Try it for a variable assignment and watch your code blow up.Ephemeral
P
2

It only matter of taste.
Use whatever you wish.

Most of time I am using second one but it depends.

Let me suggest you also to get yourself a good editor which will highlight a variable inside of a string

Purslane answered 9/4, 2011 at 15:48 Comment(1)
Ive got the textarea needed. PSPad rocks.Thoracotomy
F
1

You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.

If the variable inside the double quote PHP take time to parse variable.

Check out this Single quotes or double quotes for variable concatenation?

This is another example Is there a performance benefit single quote vs double quote in php?

I did not understand why this answer in above link get upvoted and why this answer got downvote.

As I said same thing.

You can look at here as well

What is faster in PHP, single or double quotes?

Fruma answered 9/4, 2011 at 15:42 Comment(3)
-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).Woolley
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.Purslane
Performance loss is false +1 @cHao. Here's a article with the metrics proving it. nikic.github.io/2012/01/09/…Hypochondria
V
1

I know this is an old question, but I think someone has to mention all pros & cons:

Better Syntax: That's personal preference.

Performance: No difference. As many mentioned, double-quote might be faster if using unrealistically many variables.

Better Usage: Single quote (mostly). As @Khez said, with single quote you can concatenate anything, even function calls and variable modification, like so: echo 'hi ' . trim($name) . ($i + 1);. The only thing double-quote can do that single-quote cannot do is usage of \n, \r, \t and alike.

Readability: No difference (may personal preference apply).

Writability/Re-Writability/Debugging: In 1-line statements there is no difference, but when dealing with multiple lines, it's easier to comment/uncomment lines while debugging or writing. For example:

$q = 'SELECT ' .
     't1.col1 ' .
     ',t2.col2 ' .
   //',t3.col3 ' .
     'FROM tbl1 AS t1 ' .
     'LEFT JOIN tbl2 AS t2 ON t2.col2 = t1.col1 ' .
   //'LEFT JOIN tbl3 AS t3 ON t3.col3 = t2.col2 ' .
     'WHERE t1.col1 = ' . $x . ' ' .
     '  AND t2.col2 = ' . $y . ' ' .
   //'  AND t3.col3 = ' . $z . ' ' .
     'ORDER BY t1.col1 ASC ' .
     'LIMIT 10';

Less Escaping: Single-quote. For single quote you need to escape 2 characters only (' and \). For double quote you need to escape 2 characters (", \) and 3 more if required ($, { and }).

Less Changes: Single quote. For example if you have the following code:

echo 'Number ' . $i . '!';

And you need to increment 1 to $i, so it becomes likes:

echo 'Number ' . ($i + 1) . '!';

But for double quote, you will need to change this:

echo "Number $i!";

to this:

echo "Number " . ($i + 1) . "!";

Conclusion: Use what you prefer.

Valletta answered 26/3, 2018 at 12:14 Comment(0)
S
1

If you want to execute a SQL command and your variables are array members, then you should not use single quotes inside [] of array (like this: ['']); for example if you use this string as a SQL command, you get server error 500:

$con = mysqli_connect('ServerName', 'dbUsername', 'dbPassword');
mysqli_select_db($con, 'dbName')

//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray['TraceNo']')";
mysqli_query($con, $sql)

The correct string is:

//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray[TraceNo]')";
Sell answered 23/3, 2019 at 12:12 Comment(1)
You should use PDOs insteadSosa
G
1
echo "Welcome $name!";

This is the best way.

You don't need to anything else

Griseldagriseldis answered 14/8, 2022 at 7:19 Comment(0)
C
0

for calling a class method we can use this syntax.

$type = 'Slug';

$this->{'methodName'.$type};

Callaghan answered 6/7, 2023 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.