Page 1 of 1

Use operator inside string.

Posted: Thu Jan 28, 2010 1:12 am
by fh2nov82
Hi there folks. Not sure if its possible, I'm trying to do a comparison of two values. However, the comparison operator is stored in a string. Here's what I'm trying to do.

Code: Select all

$oper = '>='; //given to me, op can be '<', '<=', '==', '>=', or '>'
$value1 = 10;
$value 2 = 15;
 
if($value1 $oper $value2) {
    statements...
}
I figured the above wouldn't work, but I'm wondering if there may be something as simple that can be done. If not I image the simplest course of action would be if..else if..else checks for each possible operator then doing the check I want to make.

Code: Select all

if($oper == '<') {
    if($value1 < $value2) {
        statements...
    }
} else if($oper == '<=') {
    if($value1 <= $vaule2) {
.....and so on
Thanks in advance for any assistance.

Re: Use operator inside string.

Posted: Thu Jan 28, 2010 6:23 am
by requinix
Can you guarantee that
- $value1 is always a number?
- $value2 is always a number?
- $oper is always one of those five operators?

Re: Use operator inside string.

Posted: Thu Jan 28, 2010 10:08 am
by AbraCadaver
Several ways to do it, probably all will need eval():

Code: Select all

$oper = '>=';
$value1 = 10;
$value2 = 15;
 
eval('$comparison = ' . $value1 . $oper . $value2 .';');
 
if($comparison) {
    //statements...
}
 
//or
 
$comparison = $value1 . $oper . $value2;
 
if(eval("return $comparison;")) {
    //statements...
}
 
I prefer this style:
 

Code: Select all

$comparison = eval("return $value1 $oper $value2;");
 
if($comparison) {
    //statements...
}

Re: Use operator inside string.

Posted: Thu Jan 28, 2010 12:05 pm
by fh2nov82
Your preferred style seems to have worked AbraCadavar, thank you very much. :)

Though I had to do it like this:
$comparison = eval('return '.$value1.' '.$oper.' '.$value2.';');

Thank you kindly for your assistance.

Thank you for your reply as well tasairis. Yes $oper will always be one of the given 5 operators, and both values are form inputs which I typecast to int before inserting into a database(along with a chosen operator). I'm running the comparison after extracting them from the database and hoping that they will both be integers ;)