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.
Go with the first and use single quotes!
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.
Either one is fine. Use the one that has better visibility for you. And speaking of visibility you can also check out printf.
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.
Do not concatenate. It's not needed, us commas as echo can take multiple parameters
Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.
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, multidimentional 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 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)