1
<?php

// expression is in variable
$var = "1+2*3/4"

// and I want it to perform and show but calculated:
echo $var; // excepted: 2.25

?>

So I have calc expressions in variable and I need then to be calculated. Is it possible?

tbodt
  • 16,609
  • 6
  • 58
  • 83
Martin Ille
  • 6,747
  • 9
  • 44
  • 63
  • Remove the quotes from around $var and it should work. since you added quotes PHP is handling this as if it was a string or in other words plain text.. Also there is no way that the solution is 2.25.. Learn about the order of operations 2*3 = 6 / 4 = 1.5 + 1 = 2.5 – Ali Aug 28 '13 at 23:47
  • To make the operation result in 2.25, you need to write it as `(1+2)*3/4` – Simon Forsberg Aug 28 '13 at 23:53
  • 1
    If you MUST keep your quotes (for whatever reason), see this: http://stackoverflow.com/questions/5057320/php-function-to-evaluate-string-like-2-1-as-arithmetic-2-1-1 – DrewP84 Aug 28 '13 at 23:54
  • 1
    A safe formula evaluator is available in ircmaxell's answer to [this question](http://stackoverflow.com/questions/12692727/how-to-make-a-calculator-in-php) – Mark Baker Aug 28 '13 at 23:59

2 Answers2

2

The way is to evaluate the expression.

echo eval('echo '.$var.';');

which gave me 2.5 bytheway.. and thats the right answer :)

Please consider that eval(); is dangerous to expose to anyone, and very hard to secure.

"echo 3+4; echo file_get_contents('index.php');"

You eval() this as a submitted string, and i have the sourcecode of your PHP. Incluing possibly your DB password, which i can now freely connect to, and dump on my screen at my whim. I can also put unlink('index.php'); in there, which is just plain destructive.

1

There is a function named eval that can deal with this but you should take great precautions when using it:

http://php.net/manual/en/function.eval.php

<?php

$var = eval("echo 1+2*3/4;");
echo $var;
// val is 2.5 (2*3/4 is calculated first, then 1 is added to the result)

$var = eval("echo (1+2)*3/4;"); 
echo $var; // val is 2.25
?>

for an explanation about why parenthesis is needed, see http://en.wikipedia.org/wiki/Order_of_operations

Most importantly you need to make sure that the string you send to eval does not contain anything that it shouldn't

eval is very dangerous to use. You have been warned

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108