Reputation: 16823
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=">">(>) - Greater than</option>
<option value="<">(<) - Less than</option>
<option value=">=">(>=) - Greater than or equal to </option>
<option value="<=">(<=) - 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 '<=':
if($column <= $value){
}
break;
}
Upvotes: 0
Views: 1605
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
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