2014-12-05 62 views
3

我初学者php。我想两个变量变量之间的算术运算

$operators = array(
    "+", 
    "-", 
    "*", 
    "/" 
    ); 

$num1 = 10; 
$num2 = 5; 

$result = $num1 . $operators[array_rand($operators)] . $num2; 

echo $result; 

它打印像这些

10+5 
10-5 

我如何才能做到这一点算术运算编辑我的代码值之间涂抹一些随机运算?

回答

5

虽然你可以使用eval()做到这一点它依赖于变量是安全的。

这是很多,安全:

function compute($num1, $operator, $num2) { 
    switch($operator) { 
     case "+": return $num1 + $num2; 
     case "-": return $num1 - $num2; 
     case "*": return $num1 * $num2; 
     case "/": return $num1/$num2; 

     // you can define more operators here, and they don't 
     // have to keep to PHP syntax. For instance: 
     case "^": return pow($num1, $num2); 

     // and handle errors: 
     default: throw new UnexpectedValueException("Invalid operator"); 
    } 
} 

现在,您可以拨打:

echo compute($num1, $operators[array_rand($operators)], $num2); 
+0

也意识到我的回答并不需要'bre​​ak',因为'return'会阻止交换机的其他部分执行。 +1 – sjagr 2014-12-05 16:38:46

0

这应该适合你!

您可以使用此功能:

function calculate_string($mathString) { 
    $mathString = trim($mathString);  // trim white spaces 
    $mathString = preg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); // remove any non-numbers chars; exception for math operators 

    $compute = create_function("", "return (" . $mathString . ");"); 
    return 0 + $compute(); 
} 

//As an example 
echo calculate_string("10+5"); 

输出:

15 

所以你的情况,你可以这样做:

$operators = array(
    "+", 
    "-", 
    "*", 
    "/" 
    ); 

$num1 = 10; 
$num2 = 5; 

echo calculate_string($num1 . $operators[array_rand($operators)] . $num2); 
+1

从[PHP文档(http://us3.php.net/manual/en /function.create-function.php)'这个函数在内部执行eval(),因此与eval()具有相同的安全问题。此外,它具有糟糕的性能和内存使用特性。“ – Jakar 2014-12-05 16:35:22

+1

Urrghh ...'create_function' – naththedeveloper 2014-12-05 16:35:23

+1

其他名字的'eval' ... – 2014-12-05 16:35:39