Why does this simple php code not work ? - echo ("$var1 + $var2 = {$var2+$var1} <br>");

Asked

Viewed 35 times

0

THE CODE IS:

echo ("$var1 + $var2 = {$var2+$var1} <br>");

both variables are recognized. compiler says '+' was not expected, but does not make sense...

php

  • As I commented on https://answall.com/a/356689/5878, when checking string interpolation, the PHP interpreter will fetch all characters from $ to construct the name of the accessed variable. From this value, you will still be able to do some operations, which include accessing a property, calling a method, or accessing a given sequence position. Mathematical operations are not allowed.

1 answer

1

This interplation with {} does not work like this in the php, if you want to do the operation do out of it and out of quotes, like this:

$var1 = 1;
$var2 = 2;
echo ("$var1 + $var2 = " . ($var2+$var1));

Or so:

echo "$var1 + $var2 = " , $var2+$var1;

And also, if you want to display the variable name, use the escape character "":

echo "\$var1 + \$var2 = "

Browser other questions tagged

You are not signed in. Login or sign up in order to post.