Hello. I've been trying to learn PHP for the past few days so I hope this isn't a silly question.

<?php
$var1 = 'lol';
$var2 = '$var1';
$var3 = eval("\$var2;");
print $var3;
?>

Basically I'm trying to eval the variable name from a string and then return the value of that variable. So in this case I'd like $var3 to have the value 'lol'.

eval is used to execute dynamic statement. like eval("\$var=7;");. It is not a fuction so the way you are using it is not correct. if you want to use variable value as variable name then you may use $$$... sign. as shown below.

<?php
$var1 = 'lol';
$var2 = 'var1';
//$var3 = eval("\$var2;");
$var3 = $$var2;

print $var3;
?>
Member Avatar for rajarajan2017

Simply execute it:

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.