Page 1 of 1
[SOLVED]Using the value of variable in the php code...
Posted: Fri Mar 09, 2007 9:38 am
by dhrosti
I'm trying to build a simple calculator in php and I have realised that I may need lots of switch statements which I cant really be bothered to do (It is Friday afternoon, after all). So i was wondering if it was possible to use the value of a variable, such as a plus sign (+) in an expression?
Posted: Fri Mar 09, 2007 9:44 am
by Maugrim_The_Reaper
If you use the variable to construct the operation as a string,
eval() could be used to evaluate it.
Posted: Fri Mar 09, 2007 10:00 am
by dhrosti
Im getting on better then i was, however its not wanting to work for me...
Code: Select all
function execute($query) {
$query2 = addslashes($query).";";
$val = eval($query2);
return $query." = ".$val;
}
For example if I were to use "3 + 7" as a query, it should execute the query as if it were part of the php code and return "3 + 7 = 10". Im getting nothing for $val at the moment though.
Posted: Fri Mar 09, 2007 10:02 am
by feyd
What's with the call to
addslashes()?
The call to
eval() should have "return" in it to receive the output of the expression.
Posted: Fri Mar 09, 2007 10:09 am
by dhrosti
Works now, thanks.
Posted: Fri Mar 09, 2007 9:44 pm
by aaronhall
I wouldn't stick that script on a public server -- someone might hax0r your internets.