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.
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.
== 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.
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.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With