dtmjl4427 2014-05-03 12:20
浏览 42

将字符串计算为条件表达式

I have an expression which looks like this:

$condition = "$foo>$bar";

and an array which has the values for the expression elements:

    array(
     'foo' => 3,
     'bar' => 4
    )

I did the replacement, in the $condition string using the str_replace() function, but the 3>4 expression returns true.

How can I properly evaluate my $condition expression in a if() statement?

  • 写回答

2条回答 默认 最新

  • dongxi3209 2014-05-03 12:22
    关注

    I have no idea why you'd want to do this, but this is technically possible. Use extract() to import the variables from the array into the current scope. Once you have the variables, you can simply compare them as usual:

    $values =array(
         'foo' => 3,
         'bar' => 4
    );
    
    extract($values);
    
    $result = $foo > $bar;
    
    if ($result) {
        echo '$foo is greater than $bar';
    } else {
        echo '$foo is not greater than $bar';
    }
    

    If $condition is a string and you can't change it, you could use eval() to evaluate the expression first:

    $condition = "$foo>$bar";
    eval(sprintf('$result = %s;', $condition));
    
    if ($result) {
        echo '$foo is greater than $bar';
    } else {
        echo '$foo is not greater than $bar';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教