0

I have a form where the user can create their own condition. E.g

<select name="operator">
    <option value="==">(==) Equal</option>
    <option value="!=">(!=) - Not Equal</option>
    <option value="&gt;">(&gt;) - Greater than</option>
    <option value="&lt;">(&lt;) - Less than</option>
    <option value="&gt;=">(&gt;=) - Greater than or equal to </option>
    <option value="&lt;=">(&lt;=) - Less than or equal to </option>
</select>

How could I parse the operator so that its actually a string but php interprets it as a condition operator?

if($column $operator $value){

}

The long winded way of doing it would be something like this:

switch($operator){
    case '!=':
        if($column != $value){

        }
    break;
    case '<=':
    case '&lt;=':
        if($column <= $value){

        }
    break;
}
John Magnolia
  • 16,769
  • 36
  • 159
  • 270
  • possible duplicate of [Using a variable as an operator](http://stackoverflow.com/questions/2263311/using-a-variable-as-an-operator) – aksu Mar 06 '14 at 07:52
  • 4
    "Short" answer: __use "long" way__. Do not use `eval()`. – Alma Do Mar 06 '14 at 07:52

2 Answers2

3

The only way to do this would to be use eval which evaluates a string as PHP code.

Using eval is generally not recommended for security reasons. Your current approach using switch is the best solution. The only other option is using if statements in a similar manner.

Mitch Satchwell
  • 4,770
  • 2
  • 24
  • 31
1

Indirect answer

Although PHP supports execution of arbitrary code, I would advise you not to do it. There are alternatives!

For this case I would advise the Strategy Pattern. It's a pattern that allows behavior to be selected at runtime. IMHO exactly what you need.

It may be a bit more work to set up than a switch statement, but it's far more flexible and maintainable.

Direct answer

You can use eval() (php.net) for this:

if (eval("return \$column $operator \$value;")) {
}

But I strongly discourage you from doing this:

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

I can't express this enough: don't use eval()!

Jasper N. Brouwer
  • 21,517
  • 4
  • 52
  • 76