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?

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;

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.