php variable substitution/expansion

We know that a variable will be substituted with its value in a “” delimited string such as:


echo “this is $var1″;

will print “this is var1″.

This variable expansion only happens when the variable name is not preceded with \. If $var is preceded with \, the \ acts as an escape character, which escapes the following $, making $ an ordinary character, and of course \ itself won’t be in the string. So the following code will print “$var2″:


echo $var2;

But we should notice that the variable substitution is not iterative. So:

echo $v1;

will print “$v3″, i.e., after $v2 is expanded to “$v3″, $v3 won’t be expanded to “v3″ any more. The following code includes a subtle error. Can you find it?


$content=”old price is $321, new price is what?”;


echo $content;

Can you figure out what the output is? Newbies may think it will print “old price is $321, new price is $123?”. Unfortunately, it is not true. The actual output is “old price is $321, new price is 3?”. Why should this happen? We should analysis the execution process of the preg_replace statement. In the first step, variables get expanded, i.e., the preg_replace statement becomes:


Note that when preg_replace is executed in the second step, $12 in the replacement string will be replaced with the captured value in the matching process, in this case, there are only two captured values: $0=what,$1=what, $2-$99 are empty. Because php only supports 100 captured values($0-$99), so $123 is recognized as {$12}3, and {$12} is substituted with the captured value “”(empty string). In the last step, the replacement string “3” is used to replace the the pattern and get the final result.

We know that php variable name can be another variable:




echo $$$c; //a


echo $a;//d

$$$c would be $$b after the first run of substitution, then $a after the second run of substitution, so $$$c is actually $a. However, this kind of substitution does not happen iteratively in a string.

echo “$$$c”;//$$b

To make the substitution iterative, you should write as this:

echo “${${$c}}”;//d

Do you think it is little bit complex to write so many curly brackets? This is actually done intentionally, to make the occurrence of the dollar currency symbol easier. Suppose you have a variable to store a price, then you want to display it with the $ prefix, you can write it as:


echo “$$price”;//$123

You does not need to include the curly brackets any more.

Posted in

Comments are closed, but trackbacks and pingbacks are open.