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 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
5 Comments
Priye Ranjan
Provided solution is working fine but it return parse error. Parse error: syntax error, unexpected ')'
Drakes
What is your real $allrule? It might have an extra parentheses.
Priye Ranjan
@Darkes My real $allrule = "(1433861812 > 1433694000) && (1433861812 > 1433771400) && (1433861812 > 1433944200)";
Priye Ranjan
@Darkes i modified it but it still gives me parse error; Can you provide the actual eval statement for provided string. $allrule = "(1433861812 > 1433694000) && (1433861812 > 1433771400) && (1433861812 > 1433944200)"
Drakes
Hello @RanjanKumar, I've added your allrule to my answer. Your allrule parses properly. (Please pardon the delay in my responding)
$allruleis a variable containing the string '(1 == 2) && (2 == 2)'.evil()or write some switch statements. But why do you want to do this?