Enclosing a variable in a doubly quoted string is the easy method of printing well meaning and clear messages for users. You may want to join some string immediately after the value supplied by variable. You may not want a blank space between the variable name and the following word. In such a situation if variable is joined with some characters not belonging to variable name, the parser will not be able to identify it. This problem can be handled with variable interpolation with curly braces.
Consider the following code where we want the counter value to be combined with word iteration in the string
<?php for ($ctr=1; $ctr<=10;$ctr++) { echo "This is $ctrIteration<BR>"; } ?>
It produces following error in browser
Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is Notice: Undefined variable: ctrIteration in C:\wamp\test\test.php on line 4 This is
Interpolation with Curly Braces
To handle such needs the variable can be interpolated by enclosing the variable name in curly brackets({}).
The updated code is
<?php for ($ctr=1; $ctr<=10;$ctr++) { echo "This is {$ctr}Iteration<BR>"; } ?>
Producing the following output
This is 1Iteration This is 2Iteration This is 3Iteration This is 4Iteration This is 5Iteration This is 6Iteration This is 7Iteration This is 8Iteration This is 9Iteration This is 10Iteration
When variable interpolation with curly braces is done it actually tells the parser about the start and end of the variable. Even if a variable name is immediately followed by a word without space the variable will be parsed and replaced with its value. PHP will evaluate a variable starting with a { and ending with a } and interpolate the rest of string as it is.