1

I am storing my condition operators in the database as we have a bunch of different conditions and it needs to be inserted in the code dynamically. So, I am pulling the condition operator from the database and then storing it in the variable. But then I need actually use the operator in my if statement. How can in insert it into if statement and use it as regular condition operator?

Here is some example of code:

$cond_operator = "<"; // (but this opperator actually pulled from database)

if ( $actual_value $cond_operator $score_value ) {
    return $result;
}
bohdan baida
  • 389
  • 1
  • 5
  • 20
  • 2
    Does this answer your question? [Dynamic Comparison Operators in PHP](https://stackoverflow.com/questions/2919190/dynamic-comparison-operators-in-php) – lainatnavi Mar 20 '20 at 17:57
  • It's not that straightforward as it looks like. " if()" statement interpreter as a true as variables not empty – bohdan baida Mar 20 '20 at 18:02

1 Answers1

4

The only way you can do what you show is with eval(). But it's generally frowned upon to use eval() because it introduces lots of potential security vulnerabilities.

I would do this hard-coded, to avoid eval() and make sure I can control the specific operators I want to support:

$cond_operator = "<"; // (but this operator actually pulled from database)

switch ($cond_operator) {
  case "<":
    if ( $actual_value < $score_value ) {
      return $result;
    }
    break;
  case ">":
    if ( $actual_value > $score_value ) {
      return $result;
    }
    break;
  case "==":
    if ( $actual_value == $score_value ) {
      return $result;
    }
    break;
  default:
    trigger_error("Unsupported condition operator: '$cond_operator'");
}
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828