Simple and Complex Strings
Posted on 6/3/07 by Tim Koschützki
There are a few simple rules when it comes to strings. To understand them, you have to know about variable interpolation.
Simple Strings
In PHP when you define simple strings using single quotes, no variable names will be interpolated. For example:
This is of course a small performance issue as well as the php interpreter does not have to look for variables to be parsed. The downsite of this is, that carriage returns (\r\n) will also not be parsed as such.
Complex String
If you want to have variables to be parsed inside a string, you have to use double quotes.
This is gives a small decrease in speed, as the php interpreter looks for variables and parses them. Of course, for small application this makes almost no difference. However, think of very large applications with many user interactions and possibly many database queries that need to parse variables. This may lead to a performance issue then.
Various ways of parsing variables in complex strings
1. Method
2. Method
3. Method
This is a very handy method, which I use often, because it makes parsing arrays easy. What for example you want to parse $arr[0] and want to append the string [0] directly afterwards?
echo "some string here $arr[0][0]";
// will generate a warning
echo "some string here {$arr[0]}[0]";
// output will be: some string here test[0]
4. Method
This is a very unusual form to php developers. Many don't even know, that it exists. I must admit I hadn't known it either for long. It was just until my php zend certification exam when a question exposing my knowledge about this variable parsing method faced me. It made me think very hard, but eventually I was correct.
You can skip to the end and add a comment.
This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.
Hi,
AFAIK the comma separated list of variables and/or values is echo command specific. It behaves as a parameter list with infinite number of optional parameters. On the other hand we cannot use brackets (parentheses) in this case.