我是php
的初学者。我试图在两个变量之间应用一些随机算术运算
$operators = array(
"+",
"-",
"*",
"/"
);
$num1 = 10;
$num2 = 5;
$result = $num1 . $operators[array_rand($operators)] . $num2;
echo $result;
它打印的值如下
10+5
10-5
如何编辑我的代码才能进行此算术运算?
答案 0 :(得分:6)
虽然您可以使用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);
答案 1 :(得分: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);