debuggable

 
Contact Us
 

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:

$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;
echo "some string here ".$var;
// 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?

$arr = array(0=>'test');

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

$var = 10;
echo "some string here ",$var;
// 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.

 
&nsbp;

You can skip to the end and add a comment.

Non_E  said on Aug 25, 2007:

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.

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.