I wrote this:
$num1 = mt_rand(1,5);
$num2 = mt_rand(1,5);
$operators = array(
"+",
"-",
"*",
"/"
);
$result = $num1 . $operators[array_rand($operators)] . $num2;
(My best guess is) This doesn't work as I expected because in the array the operator is a string which makes everything a string:
var_dump($result);
Gives:
string(3) "4+3"
So my question would be how would you recommend approaching this* without changing the logic it too much?
Thanks in advance!!
*Making random operation among random numbers, and if possible, the operators should be stored in an array.
I have the feeling my title is not correctly describing the situation but I could not come up with a better idea, I'm open to suggestions :)
The clean solution would be to have a code branch for each operator, e.g.
If you have more operators, you should create a map of
operator => function
and dynamically call the functions, for example:And of course, the unclean (slow, potentially dangerous) solution would be to use eval().
Create a function for each operation, then store operator => function name in an array.
Of course, you could use
eval
to do this, but I certainly won't settle for such a solution.I'd suggest defining a bunch of functions that take in two params and return a result, then use
call_user_func_array
on the result ofarray_rand
.