1

I have string like this: $string = "a + b + c";. Now I would like to calculate the string as sum.

For example:

$a = 10;
$b = 10;
$c = 10;
$string = "a + b + c";

echo "Result is ".$string;
output-> Result is 30

$string = "a + b * c";

echo "Result is ".$string;
output-> Result is 110


Thanks in advance

Michiel Pater
  • 22,377
  • 5
  • 43
  • 57
no_freedom
  • 1,963
  • 10
  • 30
  • 48

5 Answers5

3

I once made a calculator script.

  • It parses the calculation and puts each number and operator on a stack, in reverse polish notation.
  • It calculates the results by executing operations all operations on the stack.
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • This is the best solution I've seen that doesn't use eval(). Could use an update though, a few of the examples didn't work. Worked fine for most equations though. – jchavannes Mar 26 '13 at 20:38
3

Your question may already have been answered here on StackOverflow:

How to evaluate formula passed as string in PHP?

Community
  • 1
  • 1
Cogicero
  • 1,514
  • 2
  • 17
  • 36
2

My standard answer to this question whenever it crops up:

Don't use eval (especially as you're stating that this is user input) or reinvent the wheel by writing your own formula parser.

Take a look at the evalMath class on PHPClasses. It should do everything that you're asking, in a safe sandbox.

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

The variables in your string are missing the dollar signs. I wrote and tested a script for you that adds these signs to the variables and then parses the string as PHP code using the function eval().

$a = 10;
$b = 10;
$c = 10;
$string = "a + b + c";

$result = eval('return ' . preg_replace('/([a-zA-Z0-9])+/', '\$$1', $string) . ';');
echo $result;

This will output 30.

Michiel Pater
  • 22,377
  • 5
  • 43
  • 57
0

you can do:

$string = "$res = $a + $b + $c;";
eval($string)
echo($res);
heximal
  • 10,327
  • 5
  • 46
  • 69