1

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.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Priye Ranjan
  • 422
  • 4
  • 20

1 Answers1

3

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

Community
  • 1
  • 1
Drakes
  • 23,254
  • 3
  • 51
  • 94
  • Provided solution is working fine but it return parse error. Parse error: syntax error, unexpected ')' – Priye Ranjan Jun 09 '15 at 14:51
  • What is your real $allrule? It might have an extra parentheses. – Drakes Jun 09 '15 at 14:57
  • @Darkes My real $allrule = "(1433861812 > 1433694000) && (1433861812 > 1433771400) && (1433861812 > 1433944200)"; – Priye Ranjan Jun 09 '15 at 14:59
  • @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)" – Priye Ranjan Jun 09 '15 at 16:19
  • Hello @RanjanKumar, I've added your allrule to my answer. Your allrule parses properly. (Please pardon the delay in my responding) – Drakes Jun 10 '15 at 02:38
  • 1
    Thank You so much for your help @Darkes. – Priye Ranjan Jun 10 '15 at 10:25