Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF condtion with comparison operator stored in variable

Tags:

html

php

web

I have set of rules which involves comparison operators. I want to do some task based on the value of comparison operator stored in the rule. I am doing it in the following way but it is not working. Check the following code

if($benRules[$i]['amountCriteria']=='Greater than')
    $comparison='>';
if($benRules[$i]['amountCriteria']=='Equal to')
    $comparison='==';
if($benRules[$i]['amountCriteria']=='Less than')
    $comparison='<';

if($value['1'].$comparison.$value[$i]['2']){
    debug('Condtion checked');
}

problem is it always checks the condition to be true. it takes whole parameter inside IF condition to be string so as long as that string is not empty is executes the code inside the parenthesis. Please help me here.

like image 227
Talha Malik Avatar asked Feb 27 '26 17:02

Talha Malik


2 Answers

Your problem is that you're trying to use string as a code without evaluating it. You can use create_function() like this:

$sCondition = '<';
$mData0     = 4;
$mData1     = 5.5;
$fnCallback=create_function('$x, $y', 'return $x'.$sCondition.'$y;');
var_dump($fnCallback($mData0, $mData1)); // true

Alternatively, there is an eval() function, but it seems direct returning will be more useful in your case.

like image 197
Alma Do Avatar answered Mar 01 '26 05:03

Alma Do


It always evaluates to true as you're simply evaluating the existence of a string (you can't construct logical statements in this manner in PHP).

To achieve what you're attempting, you'd need to either use a switch statement (where you simply have a one to one match for each potential comparison operator) like so...

switch ($comparison) {
    case '<': { if($value['1'] < $value[$i]['2']) { ... } break; }
    case '==': { if($value['1'] == $value[$i]['2']) { ... } break; }
    case '>': { if($value['1'] > $value[$i]['2']) { ... } break; }
}

...or use eval to parse the logic. If might seem like a no-brainer to use the eval approach, but as the PHP manual admits:

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.

As such, if you don't understand the risks involved, please stick with the switch approach. That said, a basic solution using eval would resemble the following:

eval('return ' . $value['1'] . $comparison . $value[$i]['2'] . ';');
like image 44
John Parker Avatar answered Mar 01 '26 05:03

John Parker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!