-1

I try to evaluate a string as a condition. An example will be great:

<?php
$vars = array(
    'VAR1' => 2,
    'VAR2' => -8,
    'VAR3' => 9,
);

evaluate('VAR1 <= 0', $vars); // should return false
evaluate('VAR1 <= 0 || VAR2 < 0', $vars); // should return true
evaluate('VAR1 < 10 && (VAR2 + VAR3) >= 0', $vars); // should return true

Any idea to implement evaluate() function ?

Sony
  • 1,773
  • 3
  • 23
  • 39
  • Maybe via [`eval()`](http://php.net/eval)? – kero Mar 14 '15 at 13:03
  • `eval()` is too dirty and dangerous. – Sony Mar 14 '15 at 13:05
  • 1
    And what you are trying to do is not? – kero Mar 14 '15 at 13:05
  • 4
    You'd need to implement a parser in evaluate to break apart the string into an actual conditional if you don't want to use eval. – MasterOdin Mar 14 '15 at 13:09
  • 1
    [I answered a question](http://stackoverflow.com/a/20894727/1238344) a while back that may be useful to you: [*How can I apply my variables to a dynamic set of conditions?*](http://stackoverflow.com/questions/20893537/php-how-can-i-apply-my-variables-to-a-dynamic-set-of-conditions/20894727#20894727) – Emissary Mar 14 '15 at 13:12
  • 1
    @Sony That's stupid. `eval` is not "dirty and dangerous" if you're using it on your own data, not user-input. Nobody is going to write your hypothetical `evaluate` function for you; this question is off-topic as you haven't included any attempt at a solution, only a list of requirements. – user229044 Mar 14 '15 at 13:28
  • A [shunting yard](http://en.wikipedia.org/wiki/Shunting-yard_algorithm) parser is usually easiest to do for such basic expressions - if you really feel like reimplementing `eval` in order to satisfy a meme. – mario Mar 14 '15 at 13:29

1 Answers1

0

What about something like that:

$evaluation = sprintf('%d < 4', $var['VAR1']);  

if(assert($evaluation)){    
    echo 'true';
} else{ 
    echo 'false';
}

Sorry I wrote it quickly, I am sure you will find a better structure, also maybe if you will use often this operation could be necessary an object oriented approach.

nik.longstone
  • 244
  • 2
  • 8