37seconds Posted July 5, 2009 Share Posted July 5, 2009 I am trying to write a function that will evaluate 2 values, but the operator can be dynamic. For example: function evaluate($value1, $operator, $value2) { if ($value1 { $operator } $value2) { return true; } else { return false; } } $test = evaluate(3, ">", 1); Is there any way this can be done? Thanks in advance! Quote Link to comment https://forums.phpfreaks.com/topic/164853-convert-string-to-operator/ Share on other sites More sharing options...
cunoodle2 Posted July 5, 2009 Share Posted July 5, 2009 I don't know of a way to do it just like that but you could use a switch statement and go from there... <?php switch ($operator) { case "<": //do less than comparison here and return break; case ">": //do greater than comparison here and return break; case "==": //you get the idea break; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/164853-convert-string-to-operator/#findComment-869279 Share on other sites More sharing options...
Philip Posted July 5, 2009 Share Posted July 5, 2009 You could use eval (and the following code takes into consideration the difference between comparison & arithmetic operators.) <pre><?php function evaluate($value1, $operator, $value2) { if(in_array($operator, array('+','-','*','/','%'))) $t = 'return '.$value1.$operator.$value2.';'; else $t = 'if('.$value1.$operator.$value2.') {return true;} else {return false;}'; return eval($t); } var_dump(evaluate(3, ">", 1)); var_dump(evaluate(3, "==", 1)); var_dump(evaluate(3, "+", 1)); var_dump(evaluate(3, "-", 1)); var_dump(evaluate(3, "/", 1)); var_dump(evaluate(3, "%", 1)); ?></pre> Outputs: bool(true) bool(false) int(4) int(2) int(3) int(0) I'll be happy to add comments if you'd like. (edit for adding case examples) Quote Link to comment https://forums.phpfreaks.com/topic/164853-convert-string-to-operator/#findComment-869280 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.