-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"

2
  • Have you tried excluding the double quotes around $math in the second to last statement and concatenating, e.g. $result = $a.$math.$b; Commented Sep 11, 2015 at 16:44
  • @Craig Yes, it returns as string. Commented Sep 11, 2015 at 16:47

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.