Simple and Complex Strings
Posted by Tim Koschützki, on Mar 06, 2007 - in PHP & CakePHP » Performance, Optimization & Caching
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:
-
$var = 10;
-
echo 'some string here $var';
-
// output will be: some string here $var
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.
-
$var = 10;
-
echo "some string here $var";
-
// output will be: some string here 10
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
-
$var = 10;
-
echo "some string here $var";
-
// output will be: some string here 10
2. Method
-
$var = 10;
-
// output will be: some string here 10
3. Method
-
$var = 10;
-
echo "some string here {$var}";
-
// output will be: some string here 10
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?
4. Method
-
$var = 10;
-
// output will be: some string here 10
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.