Variable interpolation is adding variables in between when specifying a string literal. PHP will parse the interpolated variables and replace the variable with its value while processing the string literal.
I PHP, a string literal can be specified in four ways,
In this tutorial, we are going to see examples for interpolating a variable in a heredoc and with a string literal that is enclosed by double-quotes. This will show how it will be helpful in PHP string concatenation.
There are two syntaxes using which the variable interpolation can be done in PHP.
I have added an example for variable interpolation with a single word by enclosing the variable within curly braces like {$variable_name} below.
The following code shows an example for interpolating variables into a string literal 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.
In this program, I interpolated the variable in a single-quoted and double-quoted string. This is is to showcase that the variable interpolation in PHP works only with double-quoted strings.
<?php
$name = "PHPPOT";
echo "I am reading $name"; // output: I am reading PHPPOT
echo 'I am reading $name'; // output: I am reading $name
?>
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.
<?php
$name = "PHPPOT";
$myDoc = <<< EOD I am reading $name
to know all about PHP
EOD;
echo $myDoc;
?>
In this example, the $name variable is interpolated in a word. I have added the variable at the beginning of the string. We have to enclose the variable within curly brackets to interpolate them in a word.
In the below example, if there are no curly braces the variable can be misinterpreted as $namePOT. This word is a variable. So this curly syntax will be especially useful to add prefixes or suffixes to a word.
<?php
$name = "PHP";
echo "I am reading {$name}POT"; // output: I am reading PHPPOT
?>
Thank you!
Welcome Imba.
Wow and great
Thank you Abel.