[Solved]Calculating expression in string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dzim
Forum Newbie
Posts: 3
Joined: Fri Aug 05, 2005 6:34 pm
Location: Belgrade

[Solved]Calculating expression in string

Post by dzim »

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.
Last edited by dzim on Mon Aug 22, 2005 12:57 pm, edited 1 time in total.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

don't put it in quotes

Code: Select all

$cost = $price/$duration*$fix;
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
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.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

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 . ';?>');
dzim
Forum Newbie
Posts: 3
Joined: Fri Aug 05, 2005 6:34 pm
Location: Belgrade

Post by dzim »

scrotaye wrote:don't put it in quotes
It's not my decision. :)
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.
dzim
Forum Newbie
Posts: 3
Joined: Fri Aug 05, 2005 6:34 pm
Location: Belgrade

Post by dzim »

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 . ';?>');
As it says under my name, I'm a newbie. :)
I tried:

Code: Select all

eval ('$cost = $string;');
and it didn't work, of course. :)
Again, for future generations, you should use:

Code: Select all

eval('$cost ='. $string . ';');
Thanks, timvw.
Post Reply