John Magnolia
John Magnolia

Reputation: 16823

PHP parse string as condition operator

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;
}

Upvotes: 0

Views: 1605

Answers (2)

Jasper N. Brouwer
Jasper N. Brouwer

Reputation: 21817

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

Upvotes: 1

Mitch Satchwell
Mitch Satchwell

Reputation: 4830

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.

Upvotes: 3

Related Questions