gpt4 book ai didi

php - 变量之间的算术运算

转载 作者:可可西里 更新时间:2023-10-31 22:42:52 25 4
gpt4 key购买 nike

我是 php 的初学者。我正在尝试在两个变量之间应用一些随机算术运算

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

$num1 = 10;
$num2 = 5;

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

echo $result;

它打印出这样的值

10+5
10-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);

关于php - 变量之间的算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27320473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com