1

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?

Talha Can
  • 111
  • 8

4 Answers4

2

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),
    /* ... */
};
Justinas
  • 41,402
  • 5
  • 66
  • 96
2

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

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
2

If you want to piggy-back on an existing PHP function, then version_compare accepts an operator as a string:

$value1 = 10;
$value2 = 20;

var_dump(version_compare($value1, $value2, '<'));

// true

The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.

See https://3v4l.org/n0iXN

It's strictly designed for comparing version numbers (e.g 1.2.3.4), but should work fine with anything else numeric. If you don't like the name or the signature, then you can still write your own function that delegates to this, rather than white-listing each specific operator yourself.

iainn
  • 16,826
  • 9
  • 33
  • 40
1

Since you tagged this Laravel here's a little trick:

$collection = collect([ [ 'value' => $value1 ] ]);
if ($collection->where('value', $operator, $value2)->isNotEmpty()) {
   // code
}

This utilises the collection's where method which supports these operators.

This will filter the collection and keep all values which conform to "value $operator $value2". Since the collection only has one entry then the condition passes if the filtered collection is not empty

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Nice. I was wondering how Laravel implemented this internally, and it ends up being a basic switch statement, along with some special casing to work with objects: https://github.com/illuminate/collections/blob/v8.70.2/Traits/EnumeratesValues.php#L989. In case anyone else was interested. – iainn Nov 15 '21 at 08:55
  • @apokryfos Good to know. Thanks for sharing :-)! – Maik Lowrey Nov 15 '21 at 08:58