I'm storing an operator, as in '+' or '-', in a variable. For example '$operator = "-"'. I would like to do something like this: $operator = "-"; $numone = 5; $numtwo = 5; $answer = $numone $operator $numtwo; PHP: Obviously this doesn't work, but I would like to know how it could. Thanks in advance!
It displays it properly but it doesn't subtract it. So, in this example $operator = "-"; $numone = 5; $numtwo = 5; $answer = $numone.$operator.$numtwo; echo $answer; PHP: it echos '5 - 5' instead of '0'. I need it to read "-" as an operator.
$operator = "-"; $numone = 5; $numtwo = 5; $answer = eval("return($numone $operator $numtwo);"); echo $answer;
I would probably lean towards eval since it will handle any mathematical operator (%^/+-* etc...). If you don't need every function, I would definitely not use eval, because it is potentially a resource heavy function and it can be a security concern.
I have always heard eval was risky and resource hungry, but is there another way to do that without using eval? rohan_shenoy 's method would work if you knew the operations but eval would be better. Less code etc.