Hi.
I have a string:
$cost = '$price/$duration*$fix';
and I need to calculate the cost.
If I use eval() function, it just replaces variables with numbers,
but it does nothing with operators '/' and '*'.
Is there any other way to do this, except parsing it "manualy"?
Thanks.
[Solved]Calculating expression in string
Moderator: General Moderators
[Solved]Calculating expression in string
Last edited by dzim on Mon Aug 22, 2005 12:57 pm, edited 1 time in total.
don't put it in quotes
Keep in mind the order of operations will be in effect. Mulitply and divide first, then subtraction and add, then lastly, left to right
so if you want ($price/$duration)*fix or $price/($duration*fix) make sure you specify that with ()'s
Code: Select all
$cost = $price/$duration*$fix;so if you want ($price/$duration)*fix or $price/($duration*fix) make sure you specify that with ()'s
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Assuming you get the string at runtime, so there is no way to get it parsed regularly... But be careful where you get the string from, because there will be a day that people send you 'exec("rm -rf /")'
Code: Select all
$string = '$price/$duration*$fix';
eval('<?php $cost=' . $string . ';?>');It's not my decision.scrotaye wrote:don't put it in quotes
I'm getting the string from mySQL.
scrotaye wrote: Keep in mind the order of operations will be in effect. Mulitply and divide first, then subtraction and add, then lastly, left to right
so if you want ($price/$duration)*fix or $price/($duration*fix) make sure you specify that with ()'s
I will, thanks.
As it says under my name, I'm a newbie.timvw wrote:Assuming you get the string at runtime, so there is no way to get it parsed regularly... But be careful where you get the string from, because there will be a day that people send you 'exec("rm -rf /")'
Code: Select all
$string = '$price/$duration*$fix'; eval('<?php $cost=' . $string . ';?>');
I tried:
Code: Select all
eval ('$cost = $string;');Again, for future generations, you should use:
Code: Select all
eval('$cost ='. $string . ';');