我是初学者php.我试图在两个变量之间应用一些随机算术运算
$operators = array(
"+",
"-",
"*",
"/"
);
$num1 = 10;
$num2 = 5;
$result = $num1 . $operators[array_rand($operators)] . $num2;
echo $result;
Run Code Online (Sandbox Code Playgroud)
它打印这样的值
10+5
10-5
Run Code Online (Sandbox Code Playgroud)
如何编辑我的代码才能执行此算术运算?
虽然您可以使用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");
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以打电话:
echo compute($num1, $operators[array_rand($operators)], $num2);
Run Code Online (Sandbox Code Playgroud)