PHP Variable Interpolation

PHP supports interpolation of variables in between set of words to be printed to the browser using PHP output statements like echo(), print() and etc. There are two methods in variable interpolation. First method is to use variables in between string enclosed by double quotes which is shown as follows.

$name = "wearecoders";
echo "I am reading $name"; // output: I am reading wearecoders

Then, the variable interpolation can also be implemented with here document which contains several lines of string to be printed. PHP variables will be included to replace their value. A here document will be as follows to print the content as it is including line breaks, quotes and etc.

$myDoc = <<< EOD
I am reading wearecoders
to know all about PHP
EOD;
echo $myDoc;

In another method of variable interpolation, the variables will be enclosed by curly braces to replace its value inside a word that is not separated by any white space. This can be clearly understood by the following example.

$name = "PHP";
echo "I am reading {$name}wearecoders"; // output: I am reading PHPwearecoders

Here, in the above program, the variable $name is associated with the string wearecoders without any white space. So that, the curly braces are needed around the variable name to distinguish both. Otherwise, execution process will look for the variable $namewearecoders, which is no more.

Note:

  • Among both of the above two methods, the first one is the easiest method.
  • Variable interpolation is not possible with in single quotes
(Visited 35 times, 1 visits today)

Leave a Comment.