Variable interpolation in PHP

The value of a variable can be displayed as an example:

<?php
$capital = "Paris"; 

echo "The capital of France is", $capital,"<br />";
?>

But there’s a way to make it easier. If a variable name is enclosed in double (not single) quotes, the variable is interpolated. For example:

<?php
$capital = "Paris"; 

echo "The capital of France is $capital <br />";
?>

Display in the browser:

The capital of France is Paris

There is also one subtlety when using variable interpolation. For example:

<?php
$text = "news"; 
echo "Where's the $textpaper <br />"; 
?>

It is expected that the variable name $text will be replaced by its value. But the result will be an error message.

To prevent this from happening, you must specify which part of the word textpaper we have entered behind the variable name. To do this, we need to take the part we need in curly brackets:

<?php
$text = "news"; 
echo "Where's the {$text}paper <br />";
?>

Variables containing the names of other variables

In PHP, it is possible to place not only normal values, but also the names of other variables in a variable value.

<?php
$apples = 5;    // We create a variable $apples 
$fruit = "apples";    /* We create a variable $fruit, that contains the variable name $apples */ 

// Now we can output $apples as $$fruit.

echo "Number of apples - ", $$fruit;
?>

To correctly display such variables in string constants enclosed in double quotes, curly brackets should also be used: ${$fruit}. For example:

<?php
echo "Number of apples - ${$fruit}";
?>

We’ll see on the screen:

Number of apples - 5

You can comment on the article below or ask a question on Uzabila QNA.

Top ↑

Sergei Ermilov

I create web projects, come up with ideas, develop, optimize and promote websites. The first steps in this direction were taken in 2008. If you have any ideas or want to suggest something, then write to me and my team.

Leave a Reply