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;
}
2
  • possible duplicate of Using a variable as an operator Commented Mar 6, 2014 at 7:52
  • 4
    "Short" answer: use "long" way. Do not use eval(). Commented Mar 6, 2014 at 7:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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()!

2 Comments

+1 for recommending the Strategy Pattern here! But please put the eval() paragraph below your really really good point so nobody is even tempted to use the eval approach.
@thomas-david-plat Et voilà!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.