0

I have 3 variables :

$a = 5;
$b = 3
$o = "*";

The $o variable contains a string value. This value can also be "/", "+", "-".

So when I concatenate $a.$o.$b :

$result = $a.$o.$b;

echo $result;

The result is 5*3 (a string) instead of 15.

So how to convert operator string into real operator ?

totoaussi
  • 712
  • 1
  • 11
  • 27
  • 3
    `switch($o) {case '+': $result = $a + $b; break; case '-': $result = $a - $b; break; case '*': $result = $a * $b; break; case '/': $result = $a / $b; break; }` – Mark Baker Feb 12 '16 at 15:25
  • 1
    Hi Mark Baker, thank you for phpexcel, I use it ! – totoaussi Feb 12 '16 at 15:28
  • 3
    Possible duplicate of [PHP use string as operator](http://stackoverflow.com/questions/5780478/php-use-string-as-operator) – Sean Feb 12 '16 at 15:32

5 Answers5

1

You can't, you'd need to make a function or a switch statement to check each of the operators.

Read this question and its answers so you'll understand how to do it.

Community
  • 1
  • 1
Edu C.
  • 398
  • 1
  • 8
1

Simple, short and save solution:

$a = 5;
$b = 3
$o = "*";

$simplecalc = function($a,$b,$op) {
 switch($op):
  case "*":
  return $a*$b;
 case "+":
  return $a+$b;
 case "-":
  return $a-$b;
 case "/";
  return $a/$b;
 default:
  return false;
 endswitch;
};

$result = $simplecalc($a,$b,$o);
Blackbam
  • 17,496
  • 26
  • 97
  • 150
0

Actually you can do it, by using eval. But it hurts to recommend using eval, so I just give you a link to another question with a good answer: calculate math expression from a string using eval

Community
  • 1
  • 1
Tobias Xy
  • 2,039
  • 18
  • 19
0

You can use eval. For example:

eval('echo 5*3;')

will echo the number 15.

Svea
  • 267
  • 1
  • 8
0

I believe this is what you are looking for.

$a = 5;
$b = 3;
$o = "*";
$result =  eval( "echo $a$o$b;" );  
echo $result; 

Please note that using eval() is very dangerous, because it allows execution of arbitrary PHP code.

Werner
  • 449
  • 4
  • 12