-1

I want to ask how can I perform mathematics calculations with 2 random numbers ($a, $b). Im using $c as random number to clarify which mathematical symbol to use.

$a = mt_rand(1,1000);
$b = mt_rand(1,1000);
$c = mt_rand(1,1000);
if ($c < 100) {
    $math = "/";
} else if ($c > 900) {
    $math = "*";
} else if (500 < $c && $c < 900) {
    $math = "-";
} else {
    $math = "+";
}

$calculate = "$a $math $b";
echo $calculate; // provide mathematical task to user
echo "<br />";
$result = $a "$math" $b; // trying to calculate result
echo $result;

My question is how hould I use "$math" variable to clarify mathematical symbol? Thanks for the help.

Example:

$a = 1;
$b = 2;
$math = "*";

Result is "1 * 2"

Arnas Marnas
  • 43
  • 1
  • 1
  • 6

1 Answers1

1

To calculate the result, you can use eval() by changing these lines:

$result = $a "$math" $b; // trying to calculate result
echo $result;

to:

$calculatePHP = '$result = ('.$a.$math.$b.');';
eval($calculatePHP);
echo $result;
uri2x
  • 3,162
  • 1
  • 11
  • 25