Marco
Marco

Reputation: 644

have a condition in a variable in PHP

I am passing a condition as a string to my method and I want to use it inside an if statement like so but it doesn't seem to work.

// $condition could be a > or < or == etc...
if (!( $field $condition $value )) {
         //code here
}

Is there a way to do this in PHP. I have tried wrapping $condition in curly brackets but does not work.

many thanks in advance

Upvotes: 0

Views: 116

Answers (2)

Ckankonmange
Ckankonmange

Reputation: 111

Passing a condition as a string is not recommended, it could lead to majors security breachs.

I would recommand to change your architecture or use some kind of enumeration (this could help you) in addition to a switch case.

Upvotes: 1

user1119648
user1119648

Reputation: 541

This is a terrible idea. The best way to handle this is a switch statement.

switch ($condition) {
    case ">":
        return $field > $value;
    case "<"
        return $field < $value;
    default:
        return false;
}

Any other method is going to be a hack, hard to maintain, or insecure.

Upvotes: 3

Related Questions