For example:
Code: Select all
function evaluate($value1, $operator, $value2)
{
if ($value1 { $operator } $value2)
{
return true;
}
else
{
return false;
}
}
$test = evaluate(3, ">", 1);
Thanks in advance!
Moderator: General Moderators
Code: Select all
function evaluate($value1, $operator, $value2)
{
if ($value1 { $operator } $value2)
{
return true;
}
else
{
return false;
}
}
$test = evaluate(3, ">", 1);
Code: Select all
<?php
$a = 32;
$b = 42;
$operator = '>';
$conditional_operators = array('==', '===', '!=', '!==', '<>', '<', '>', '<=', '>=');
$result = null;
if (in_array($operator, $conditional_operators) && is_numeric($a) && is_numeric($b)) {
eval("\$result = (\$a $operator \$b);");
}
var_dump($result); // Should be true, false, or null
?>Code: Select all
function evaluate($value1, $operator, $value2)
{
$result = false;
switch($operator) {
case '=' :
case '==' :
$result = ($value1 == $value2);
break;
case '!=' :
$result = ($value1 != $value2);
break;
case '>' :
$result = ($value1 > $value2);
break;
case '>=' :
$result = ($value1 >= $value2);
break;
...
}
return $result;
}
$test = evaluate(3, ">", 1);
For most people I'd agree, but there are some of us who know what we're doing. Blindly saying things like "eval is bad" - I used to myself - isn't fair.Mark Baker wrote:Avoid eval() like the plague. Bad habits (even when the data is safe) lead to bad habits when it is unsafe.
Even when there are circumstances where the use of eval() might not be considered bad, there are generally better alternatives (or at least alternatives), e.g. perhaps a lambda function (nearly as "dirty", though it's not particularly efficient).tasairis wrote:For most people I'd agree, but there are some of us who know what we're doing. Blindly saying things like "eval is bad" - I used to myself - isn't fair.
Code: Select all
$conditional_operators = array('==', '===', '!=', '!==', '<>', '<', '>', '<=', '>=');
$result = null;
if (in_array($operator, $conditional_operators) && is_numeric($a) && is_numeric($b)) {
$comparator = create_function('$a,$b','return ($a '.$operator.' $b);');
return $comparator($a,$b);
}
Code: Select all
Call time for Case Evaluation was 0.0352 seconds
Call time for Eval Evaluation was 0.2457 seconds
Call time for Lambda Function Evaluation was 0.7116 seconds