Jump to content

Calculating with Operator Inside Variable?


chaseman

Recommended Posts

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?

Link to comment
Share on other sites

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;

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.