PHP Variable Interpolation

by Vincy. Last modified on May 4th, 2017.

Variable interpolation is adding variables in between a string data. PHP will parse the interpolated variables and replace the variable with its value while processing the string data. The variable parsing is allowed with the string data enclosed with double quotes or with heredocs. Since, the variable interpolation will not be effective with the single quoted string or nowdocs, since it doesn’t support variable parsing.

In this tutorial, we are going to see examples for interpolating a variable in a heredoc and with a string data that is enclosed by double quotes. Also, I have added an example for variable interpolation with a single word by enclosing the variable within curly braces like {$variable_name}. This will be useful for adding prefix or suffix to a word. 


Variable Interpolation in a String

The following code shows an example for interpolating variable into a string that is enclosed in double quotes. In this example, I have a string variable containing the value ‘PHPPOT’ which is interpolated into the echo statement to parse this variable on printing data to the browser. In this program, I interpolated the variable in a single quoted string and shows the resultant string with the PHP variable as it is without parsing its value. 

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

Variable interpolation with heredoc

The code has a heredoc statement. In this statement, I added multiple lines of string data and interpolated the $name variable into it. While printing this statement the PHP variable is parsed to print the value. After variable parsing, the heredoc statement will be printed with the line breaks as specified.

$name = "PHPPOT";
$myDoc = <<< EOD I am reading $name
to know all about PHP 
echo $myDoc;

Interpolating Variable in a Word

In this example, the $name variable is interpolated in a word. I have added the variable in the beginning of the string. We have to enclose the variable within curly brackets to interpolate them in a word. This will be useful to add common prefix or suffix to a word.

$name = "PHP";
echo "I am reading {$name}POT"; // output: I am reading PHPPOT

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top