在5行以及2列表生成器上遇到php Random Math和operator generator问题

So far I have this to generate random numbers, and I need it to generate random operators, in which it just scrolls through the array and gives off the same 2 operators.

So instead of generating 5 lines it generates about 12. I can get it to show the operator in the math problem but I cannot get the operators to randomize on each line. Something is wrong somewhere.

I also have to have the problem generate in two column table where it has problem in one column and solution in the other. If someone can at least point me in the right direction it would be much appreciated!

<?php
for ($x = 0; $x <= 5; $x++) {
    $num1 = mt_rand(1, 9);
    $num2 = mt_rand(1, 9);

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

    switch ($operators[array_rand($operators)]) {
        case "+":
            $result = $num1 + $num2;
            break;
        case "-":
            $result = $num1 - $num2;
            break;
    }
    foreach($operators as $value){
        echo "$num1 $value $num2 = $result <br>";
    }
}
?>

Try this way:

for ($x = 0; $x <= 5; $x++) {
$num1 = mt_rand(1, 9);
$num2 = mt_rand(1, 9);

$operators = array("+","-",);
$value = $operators[array_rand($operators)];

switch ($value) {
case "+":
    $result = $num1 + $num2;
    break;
case "-":
    $result = $num1 - $num2;
    break;
}
    echo "$num1 $value $num2 = $result <br>";
}
  1. You don't need to iterate $operators, since you are picking random one.
  2. There is no need to re-create $operators in the loop.
  3. If the code is supposed to output 5 lines, then the for condition should be changed to $x < 5 (instead of $x <= 5).

Fixed version

<?php
$operators = ["+", "-"];

for ($x = 0; $x < 5; $x++) {
  $num1 = mt_rand(1, 9);
  $num2 = mt_rand(1, 9);

  $k = array_rand($operators);
  switch ($operators[$k]) {
  case "+":
    $result = $num1 + $num2;
    break;
  case "-": // break
  default:
    $result = $num1 - $num2;
    break;
  }
  echo "$num1 {$operators[$k]} $num2 = $result<br/>
";
}