简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM