Home > Enterprise >  PHP Dynamic operator usage
PHP Dynamic operator usage

Time:11-15

I want to be able to use the operator between two values ​​according to the value that will come from the database.

For ex:


$operator = '<='; // this can be '<=' or '<' or '>=' etc.

// I need like this something
if ($value1 $operator $value2) {
    //
}

How can i do?

CodePudding user response:

You need map all possible values to actual code, because eval is evil

$result = match ($operator) {
    '>=' => $this->doStuff($value1 >= $value2),
    '>' => $this->doStuff($value1 > $value2),
    '=', '==', '===' => $this->doStuff($value1 === $value2),
    /* ... */
};

CodePudding user response:

You can write a function with a switch case inside. like that:

$operator = '<='; // this can be '<=' or '<' or '>=' etc.

// I need like this something
$value1 = 2;
$value2 = 3;


function dyn_compare ($var1, $operator, $var2) {
    switch ($operator) {
        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;
    }   
}

//Then you can use

if (dyn_compare($value1, $operator, $value2)) {
    echo 'yes';
}

Alternatively you can work with match like @Justinas suggested. But this only works with php 8 and upwards

  • Related