Dynamic Comparison Operators in PHP
You can also use version_compare() function, as you can pass operator which will be used for comparison as third argument.
How about this one?
function num_cond ($var1, $op, $var2) {
switch ($op) {
case "=": return $var1 == $var2;
case "!=": return $var1 != $var2;
case ">=": return $var1 >= $var2;
case "<=": return $var1 <= $var2;
case ">": return $var1 > $var2;
case "<": return $var1 < $var2;
default: return true;
}
}
Test:
$ops = array( "=", "!=", ">=", "<=", ">", "<" );
$v1 = 1; $v2 = 5;
foreach ($ops as $op) {
if (num_cond($v1, $op, $v2)) echo "True ($v1 $op $v2)\n"; else echo "False ($v1 $op $v2)\n";
}
How about a small class:
class compare
{
function is($op1,$op2,$c)
{
$meth = array('===' => 'type_equal', '<' => 'less_than');
if($method = $meth[$c]) {
return $this->$method($op1,$op2);
}
return null; // or throw excp.
}
function type_equal($op1,$op2)
{
return $op1 === $op2;
}
function less_than($op1,$op2)
{
return $op1 < $op2;
}
}