Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Comparison Operators in PHP

Is it possible, in any way, to pass comparison operators as variables to a function? I am looking at producing some convenience functions, for example (and I know this won't work):

function isAnd($var, $value, $operator = '==')
{
    if(isset($var) && $var $operator $value)
        return true;
}

if(isAnd(1, 1, '===')) echo 'worked';

Thanks in advance.

like image 666
BenTheDesigner Avatar asked May 27 '10 07:05

BenTheDesigner


People also ask

What are the 5 comparison operators?

Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== . Logical operators — operators that combine multiple boolean expressions or values and provide a single boolean output.

What is == and === in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. Syntax: operand1 == operand2. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

What are the 6 comparison operators?

Summary. In today's python comparison operators article by TechVidvan, we saw the six comparison operators of Python named as less than, greater than, less than or equal to, greater than or equal to, equal to and not equal to operator.


2 Answers

You can also use version_compare() function, as you can pass operator which will be used for comparison as third argument.

like image 88
alokin Avatar answered Sep 28 '22 09:09

alokin


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";
}
like image 28
Goran Avatar answered Sep 28 '22 08:09

Goran