我是php
的初学者。我试图在两个变量之间应用一些随机算术运算。
$operators = array(
"+",
"-",
"*",
"/"
);
$num1 = 10;
$num2 = 5;
$result = $num1 . $operators[array_rand($operators)] . $num2;
echo $result;
它打印如下的值
10+5
10-5
如何编辑我的代码才能完成这个算术操作?
发布于 2014-12-05 16:35:08
虽然您可以使用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);
发布于 2014-12-05 16:32:39
这应该对你有用!
您可以使用此函数:
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);
https://stackoverflow.com/questions/27320473
复制相似问题