chaseman Posted March 1, 2011 Share Posted March 1, 2011 I'm trying to build a math game. But I'm having trouble trying to make a variable calculate that contains an operator. Example: $c1_op = "+"; $a1_num_user = $_POST['a1_num']; $e1_num_user = $_POST['e3_num']; $row_1 = $a1_num_user . $c1_op . $e1_num_user; echo "result: " . $row_1; If I now input a 10 and a 2 I will get echo'd out: result: 10+2 It's not calculating. When I don't use any quotation marks then I will get the error "unexpected ;". I need the operator inside a variable, it's the nature of the math game, any idea how I can make it work so it calculates? Quote Link to comment https://forums.phpfreaks.com/topic/229294-calculating-with-operator-inside-variable/ Share on other sites More sharing options...
AbraCadaver Posted March 1, 2011 Share Posted March 1, 2011 $row_1 = eval("return $a1_num_user $c1_op $e1_num_user;"); Quote Link to comment https://forums.phpfreaks.com/topic/229294-calculating-with-operator-inside-variable/#findComment-1181465 Share on other sites More sharing options...
.josh Posted March 1, 2011 Share Posted March 1, 2011 okay so there are a couple ways to go about this. One is by making use of eval() as AC has shown. I don't really recommended doing this because it opens up for a lot of potential security issues. eval() executes whatever string you pass it as php code. So the user can enter in php code and eval will execute it. One alternative to setup a condition like so: $c1_op = "+"; $a1_num_user = $_POST['a1_num']; $e1_num_user = $_POST['e3_num']; switch($c1_op) { case '+' : $row_1 = $a1_num_user + $e1_num_user; break; case '-' : $row_1 = $a1_num_user - $e1_num_user; break; // etc... } echo "result: " . $row_1; Quote Link to comment https://forums.phpfreaks.com/topic/229294-calculating-with-operator-inside-variable/#findComment-1181469 Share on other sites More sharing options...
chaseman Posted March 1, 2011 Author Share Posted March 1, 2011 Every time eval comes up I think of evil because people mention the security issues Your case example worked great though, thanks a lot. Quote Link to comment https://forums.phpfreaks.com/topic/229294-calculating-with-operator-inside-variable/#findComment-1181473 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.