操作员不工作

时间:2012-10-19 13:04:26

标签: php

我在字符串中有一个运算符。

 $c['operator'] = ">=";

        if($sub_total.$c['operator'].$c['value'])
        {
        echo $sub_total.$c['operator'].$c['value'];

        }

它获得的输出为20610>=30000

6 个答案:

答案 0 :(得分:4)

我将可能的运算符放在switch

$result = null;

switch($c['operator'])
{

    case '>=':
        $result = $sub_total >= $c['value'];
    break;
    case '<=':
        $result = $sub_total <= $c['value'];
    break;

    // etc etc

}

这比使用eval更安全,并且具有清理输入的额外好处。

答案 1 :(得分:1)

除非您使用eval(请注意它),否则不能将字符串解释为PHP代码。

您在if语句中的示例中所做的是连接字符串,因为连接后的字符串不是null,它被评估为true,所以if语句被执行。

在你的情况下,解决方案是看看@adam在他的解决方案中使用了哪个运算符。

顺便说一句,在字符串中使用逻辑(可能在脚本之外)并不是一个好主意。

答案 2 :(得分:1)

$sub_total.$c['operator'].$c['value']不是比较,而是字符串连接。填充的字符串在PHP中始终为true,因此if - 语句始终为true

答案 3 :(得分:0)

使用PHP eval评估您构建的代码。

$c['operator'] = ">=";

if(eval($sub_total.$c['operator'].$c['value']))
{
    echo $sub_total.$c['operator'].$c['value'];          
} 

答案 4 :(得分:0)

您无法在PHP中执行此操作,您应该执行以下操作:

if ($c['operator'] == '>=' and $sub_total >= $c['value']) {
    // Do something
} else if ($c['operator'] == '<=' and $sub_total <= $c['value']) {
    // Do something else
} // etc...

答案 5 :(得分:0)

看一下eval方法。

虽然很危险

http://php.net/manual/en/function.eval.php