0

I have dynamic condition for if statement that stored as a variable. How to make if statement worked using that variable as as its condition?

I have tried using eval function but it's still didn't work

Here is my code:

$a = 2;
$b = 2;
$c = '$a==$b';
$d = eval('return $c;');

if($d === true){
    echo 'yes';
}
else{
    echo 'no';
}

It should be return 'yes', but my current code return 'no'.

Kevin A.S.
  • 123
  • 7

2 Answers2

1

You just need to use double quotes instead of single quote

<?php
$a = 2;
$b = 2;
$c = "$a==$b";
$d = eval("return $c;");

if($d === true){
    echo 'yes';
}
else{
    echo 'no';
}
?>
vivek modi
  • 487
  • 1
  • 5
  • 19
0

After some experiments, I have found this solution. So what I need to do is put the eval function inside if condition:

<?php
$a = 2;
$b = 2;
$c = '$a==$b';

if(eval("return $c;")){ //must using double quotes
    echo 'yes';
}
else{
    echo 'no';
}
Kevin A.S.
  • 123
  • 7