...

View Full Version : eval and math functions



mathceleb
04-01-2010, 05:58 PM
There seems to be a rift between programmers whether eval on math strings works or it does not.


$str="(6 - 4)";
$num=eval($str);


My question is, should $num = 2, or is eval not the way to go?
When I try the above, $num comes up empty.

I have a function which splits off each number and sign, and then evaluates the math, but wanted to get a second opinion on the whole eval argument.

Fou-Lu
04-01-2010, 06:39 PM
That would return null, but it has a parse error from the looks of it.
Eval works (btw, eval is the ONLY function in PHP that I recall always fails for me the first time I write it) by parsing what its given as PHP code.
The above will not work, since (6 - 4) is not evaluatable in PHP. What is evaluable is (6 - 4);, but still will result in null.
In order to store the result, you must either return the data (oh jeez, this will probably fail the first time :P) with $str = "return (6 - 4);"; to return it to $num, or you can lump it as the result directly within the eval: eval("\$num = \"$str\";");.
Crossing my fingers that either of those work on the first try hah! Also, try to limit you're usage of eval, since it is slower and open to exploitation.

kbluhm
04-01-2010, 06:50 PM
This should do it:


$str = '(6 - 4)';

eval( '$sum = ' . $str . ';' );

var_dump( $sum ); // int(2)

mathceleb
04-01-2010, 07:45 PM
Found something similar and it works:


$cur="(6 - 4)";
eval("\$value=".$cur.";");
echo $cur . " = " . $value . "<br />";

This prints (6 - 4) = 2.

Thanks!

Fou-Lu
04-01-2010, 08:03 PM
Found something similar and it works:


$cur="(6 - 4)";
eval("\$value=".$cur.";");
echo $cur . " = " . $value . "<br />";

This prints (6 - 4) = 2.

Thanks!

How about mine, did either work? I'm just curious since I have yet to get eval to work the first time :$



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum