0

Maybe there is a topic about this, but I coudn't find.

I'm storing in a database a comparative operator and a target value, like:

$target_value_1 => 1000

$operator => greather_than_or_equal

Is there a way of using those operators in a variable like:

if ($variable1 $operator $target_value_1){

    // Some code

}

Working with PHP and MySQL.

Thanks

tadman
  • 208,517
  • 23
  • 234
  • 262
Marcos Felipe
  • 100
  • 13
  • 1
    Possible Dupe? [Using a variable as an operator](https://stackoverflow.com/questions/2263311/using-a-variable-as-an-operator) – ficuscr Mar 21 '18 at 18:13

1 Answers1

1

I'm not sure what are you building but you can sort this by simply creating a check($operator, $var1, $var2) function along these lines :

function check($operator, $val1, $val2) {
    switch ($operator) {
    case 'greather_than_or_equal':
        return $val1 >= $val2;
        break;
    case 'greather_than':
        return $val1 > $val2;
        break;
    case 'operator_name':
        //return your condition goes here;
        break;
    default:
        return false;
        break;
    }
}

And use it : if (check($operator, $value1, $value2)) { /* your code */ }

mrbm
  • 2,164
  • 12
  • 11
  • Thanks for your answer. I was thinking of getting around this way, but first I'd like to check if there wasn't a shortter and cleaner way to do it. – Marcos Felipe Mar 21 '18 at 18:24
  • Say you have defined the function `greather_than_or_equal($a, $b) {return $a>=$b;}`, you can do use is later as `if ($operator($variable1, $target_value_1)) { ..` you can define your operators as functions this way but it's way less cleaner/readable in my opinion. – mrbm Mar 21 '18 at 18:30