Martin Ille
Martin Ille

Reputation: 7055

How to calculate from variable

<?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?

Upvotes: 1

Views: 108

Answers (2)

Thomas Martin Klein
Thomas Martin Klein

Reputation: 444

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.

Upvotes: 2

Simon Forsberg
Simon Forsberg

Reputation: 13331

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

Upvotes: 1

Related Questions