how to make dynamic conditions in operators in if conditions

Viewed 243

I have to make filters in which every condition is dynamic like greater than, less than equal to with && and || operator for that I have made below code

    <?php
    $a = 5;
    $b = 2;
    $grater = '<';
    $equal = '==';
    $and = '&&';
    
    if(($a .$equal. $b)){
        echo 'hii';
    }else{
        echo 'hello';
    }
?>

but when I use this code it is not working properly. can anybody help me in this

4 Answers

You could use a match expression like this:

function compute($operator, $a, $b)
{
    return match ($operator) {
        '<'  => ($a <  $b),
        '==' => ($a == $b),
        '&&' => ($a && $b),
    };
}

var_dump(compute('==', 5, 2));

This has three advantages:

  1. You avoid the use of eval().
  2. It will also work with strings.
  3. It is easy to expand to other operators.

if you concate strings into condition, this will result to string, so you will not get if(5 == 2) but you will get if("5 == 2") and this will be always true, because php will evaluate any non empty string as true. You need to eval this string, for example: if(eval($a . $equal . $b)) but using eval is bad practise https://www.php.net/manual/en/function.eval.php

Try this:

if (eval("($a . $equal . $b)"))

You can do this with eval, as other answers suggested. If you choose this path, note that you will need to protect against PHP injection, which is, by itself a very complex topic. You will need to validate both the operands and the operators. While that's possible and, assuming it's properly validated it would be safe as well, it is an unclean, hacky solution and you will always have to worry about PHP code injection, whenever you change the code, you will need to change the validator as well, with danger always looming around.

As a result, I propose the implementation of functions, such as:

function equal($a, $b, $strict = false) {
    return $strict ? ($a === $b) : ($a == $b);
}

and then you can do something of the like:

if (equal($a, $b)) {
    //...
}
Related