如何在数组中放置运算符


How to put operators in array?

我想制作一个简单的程序,为一些数字更改运算符"+"、"-"、"*"、"/"。所以,我把运算符放在数组中,并尝试通过循环来迭代它们。

$num1 = 10;
$num2 = 20;
$operators = array("+", "-", "*", "/");
for ($x=0;$x<=count($operators)-1;$x++){
echo $num1 . $operators[$x] .  $num2 . "</br>";
}

它显示:

10+5
10-5
10*5
10/5

乍一看,这似乎还可以,但我需要计算数字,执行运算,简单地说,我需要最终结果数字,这给了我4个字符串。我理解其中的原因:$operators数组中的值是字符串,而不是真正的运算符。我的问题是,如何将实数运算符放入数组中,或者,我可以将它们作为字符串保留在数组中,但在输出时以某种方式将它们转换为实数运算符?这两种战略的解决方案都是受欢迎的。提前感谢!

也许您可以尝试以下方法:

for ( $x=0; $x < count($operators); $x++ ){
    switch($operators[$x]){
        case '+':$answer=$num1+$num2;break;
        case'-':$answer=$num1-$num2;break;
        case '*':$answer=$num1*$num2;break;
        case'/':$answer=$num1/$num2;break;
    }
    echo $answer;
}

不能在数组中放入实数运算符,因为它是语言构造。但你可以放这样的函数(我使用匿名函数,你可以使用命名函数)

$operations = array(
    '+' => function ($a, $b) { return $a + $b; }
);
foreach ($operations as $sign => $func) {
   echo '10'.$sign.'5 = '. $func(10, 5)."'n";
}

你可以试试这个

$num1 = 10;
$num2 = 20;
$operators = array("+", "-", "*", "/");
for ($x=0;$x<=count($operators)-1;$x++){
    echo eval('return '.$num1 . $operators[$x] .  $num2 . ';')."</br>";
}