I am wondering, What is the proper way for inserting PHP variables into a string?
This way:
echo \"Welcome \".$name.\"!\"
Either one is fine. Use the one that has better visibility for you. And speaking of visibility you can also check out printf.
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
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.
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) . "!";
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}";
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()