Convert string to variable in PHP

632 views Asked by At

I have a variable $allrule = '(1 == 2) && (2 == 2)'; when i check if($allrule), it returns true because $allrule is treated as string. So i want to convert $allrule as condition of if statement. how can we do it.

1

There are 1 answers

5
Drakes On BEST ANSWER

This solution uses eval() which is pure evil, but since it wasn't stipulated not to do so...

$allrule = '(1 == 2) && (2 == 2)';
$result = eval("return (".$allrule.");"); // $result will be false

Expanded Example*:

$allrule = "(1433861812 > 1433694000) && (1433861812 > 1433771400) && (1433861812 > 1433944200)";

$result = eval("return (".$allrule.");");
if($result) {
    echo "true";
} else {
    echo "false"; // will echo "false"
}

*from comments